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
1334G
1334
G
ru
G. Поиск подстроки
<div class="problem-statement"><div class="header"><div class="title">G. Поиск подстроки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.25 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана перестановка $$$p$$$, состоящая из $$$26$$$ целых чисел от $$$1$$$ до $$$26$$$ (так как это перестановка, каждое число от $$$1$$$ до $$$26$$$ встречается в $$$p$$$ ровно один раз), а также две строки $$$s$$$ и $$$t$$$, состоящие из строчных букв латинского алфавита.</p><p>Подстрока $$$t'$$$ строки $$$t$$$ является <span class="tex-font-style-bf">вхождением</span> строки $$$s$$$, если выполняются следующие условия:</p><ol> <li> $$$|t'| = |s|$$$; </li><li> для каждого $$$i \in [1, |s|]$$$ либо $$$s_i = t'_i$$$, либо $$$p_{idx(s_i)} = idx(t'_i)$$$, где $$$idx(c)$$$ — номер символа $$$c$$$ в латинском алфавите ($$$idx(\text{a}) = 1$$$, $$$idx(\text{b}) = 2$$$, $$$idx(\text{z}) = 26$$$). </li></ol><p>Например, если $$$p_1 = 2$$$, $$$p_2 = 3$$$, $$$p_3 = 1$$$, $$$s = \text{abc}$$$, $$$t = \text{abcaaba}$$$, три подстроки $$$t$$$ являются вхождениями $$$s$$$ ($$$t' = \text{abc}$$$, $$$t' = \text{bca}$$$ и $$$t' = \text{aba}$$$).</p><p>Для каждой подстроки $$$t$$$ с длиной, равной $$$|s|$$$, проверьте, является ли она <span class="tex-font-style-bf">вхождением</span> строки $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы $$$26$$$ целых чисел $$$p_1$$$, $$$p_2$$$, ..., $$$p_{26}$$$ ($$$1 \le p_i \le 26$$$, все эти числа попарно различны).</p><p>Во второй строке задана строка $$$s$$$, а в третьей — строка $$$t$$$ ($$$2 \le |s| \le |t| \le 2 \cdot 10^5$$$), обе они состоят из строчных латинских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите строку из $$$|t| - |s| + 1$$$ символов, каждый из которых должен быть либо <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>. $$$i$$$-й символ должен быть <span class="tex-font-style-tt">1</span> тогда и только тогда, когда подстрока $$$t$$$, начинающаяся с $$$i$$$-го символа и заканчивающаяся $$$(i + |s| - 1)$$$-м символом (включительно), является <span class="tex-font-style-bf">вхождением</span> строки $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 abc abcaaba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11001</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="5987e0692abd1b29494fa712217ca6ae"/> <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="cc220c300d2bb3e2ce9ed49eed38912086754c3f"/> <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='5987e0692abd1b29494fa712217ca6ae'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1334%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='5987e0692abd1b29494fa712217ca6ae'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1334">Educational Codeforces Round 85 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='5987e0692abd1b29494fa712217ca6ae'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1334/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье"> бпф </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='5987e0692abd1b29494fa712217ca6ae'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590687"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5987e0692abd1b29494fa712217ca6ae'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590687"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75793" title="Educational Codeforces Round 85 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10751:10752" 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/75877" title="Разбор Educational Codeforces Round 85" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10755:10756" 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/1334">Задачи</a></li> <li><a href="/contest/1334/submit">Отослать</a></li> <li><a href="/contest/1334/my">Мои посылки</a></li> <li><a href="/contest/1334/status">Статус</a></li> <li><a href="/contest/1334/hacks">Взломы</a></li> <li><a href="/contest/1334/standings">Положение</a></li> <li><a href="/contest/1334/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f6c2fbd103dc5982a7e4c97dcc631caebbd823da"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Поиск подстроки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.25 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана перестановка $$$p$$$, состоящая из $$$26$$$ целых чисел от $$$1$$$ до $$$26$$$ (так как это перестановка, каждое число от $$$1$$$ до $$$26$$$ встречается в $$$p$$$ ровно один раз), а также две строки $$$s$$$ и $$$t$$$, состоящие из строчных букв латинского алфавита.</p><p>Подстрока $$$t'$$$ строки $$$t$$$ является <span class="tex-font-style-bf">вхождением</span> строки $$$s$$$, если выполняются следующие условия:</p><ol> <li> $$$|t'| = |s|$$$; </li><li> для каждого $$$i \in [1, |s|]$$$ либо $$$s_i = t'_i$$$, либо $$$p_{idx(s_i)} = idx(t'_i)$$$, где $$$idx(c)$$$ — номер символа $$$c$$$ в латинском алфавите ($$$idx(\text{a}) = 1$$$, $$$idx(\text{b}) = 2$$$, $$$idx(\text{z}) = 26$$$). </li></ol><p>Например, если $$$p_1 = 2$$$, $$$p_2 = 3$$$, $$$p_3 = 1$$$, $$$s = \text{abc}$$$, $$$t = \text{abcaaba}$$$, три подстроки $$$t$$$ являются вхождениями $$$s$$$ ($$$t' = \text{abc}$$$, $$$t' = \text{bca}$$$ и $$$t' = \text{aba}$$$).</p><p>Для каждой подстроки $$$t$$$ с длиной, равной $$$|s|$$$, проверьте, является ли она <span class="tex-font-style-bf">вхождением</span> строки $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы $$$26$$$ целых чисел $$$p_1$$$, $$$p_2$$$, ..., $$$p_{26}$$$ ($$$1 \le p_i \le 26$$$, все эти числа попарно различны).</p><p>Во второй строке задана строка $$$s$$$, а в третьей — строка $$$t$$$ ($$$2 \le |s| \le |t| \le 2 \cdot 10^5$$$), обе они состоят из строчных латинских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите строку из $$$|t| - |s| + 1$$$ символов, каждый из которых должен быть либо <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>. $$$i$$$-й символ должен быть <span class="tex-font-style-tt">1</span> тогда и только тогда, когда подстрока $$$t$$$, начинающаяся с $$$i$$$-го символа и заканчивающаяся $$$(i + |s| - 1)$$$-м символом (включительно), является <span class="tex-font-style-bf">вхождением</span> строки $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 abc abcaaba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11001</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 11:00: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:'81249c880fd80c48',t:'MTY5NjY2NTYzNy4yMTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0431\u043f\u0444", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2900"]
1335A
1335
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$$$ конфет. Вам хочется распределить все эти $$$n$$$ конфет между сёстрами так, что:</p><ul> <li> Алиса получит $$$a$$$ ($$$a &gt; 0$$$) конфет; </li><li> Бетти получит $$$b$$$ ($$$b &gt; 0$$$) конфет; </li><li> каждая сестра получит некоторое <span class="tex-font-style-bf">целое</span> количество конфет; </li><li> Алиса получит больше конфет, чем Бетти (то есть $$$a &gt; b$$$); </li><li> все конфеты будут отданы одной из двух сестёр (то есть $$$a+b=n$$$). </li></ul><p>Ваша задача — посчитать количество способов распределить $$$n$$$ конфет между девочками так, как описано выше. Учтите, что конфеты неразличимы между собой.</p><p>Формально, найдите количество способов представить $$$n$$$ как сумму $$$n=a+b$$$, где $$$a$$$ и $$$b$$$ — положительные целые числа и $$$a&gt;b$$$.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$) — количество конфет, которое у вас есть.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — количество способов распределить ровно $$$n$$$ конфет между девочками так, как описано в условии задачи. Если не существует способа, удовлетворяющего всем условиям, выведите $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 7 1 2 3 2000000000 763243547 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 0 1 999999999 381621773 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора тестовых данных возможные $$$3$$$ способа распределения конфет — это:</p><ul> <li> $$$a=6$$$, $$$b=1$$$; </li><li> $$$a=5$$$, $$$b=2$$$; </li><li> $$$a=4$$$, $$$b=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="3652e2193c2818065a3e8e51c3b14340"/> <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="02d43bcc2dd3b25149c439050237c87344017840"/> <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='3652e2193c2818065a3e8e51c3b14340'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1335%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='3652e2193c2818065a3e8e51c3b14340'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1335">Codeforces Round 634 (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='3652e2193c2818065a3e8e51c3b14340'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1335/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='3652e2193c2818065a3e8e51c3b14340'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="592971"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3652e2193c2818065a3e8e51c3b14340'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="592971"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75908" title="Codeforces Round #634 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10762:10763" 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/75993" title="75993" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10765:10766" 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/1335">Задачи</a></li> <li><a href="/contest/1335/submit">Отослать</a></li> <li><a href="/contest/1335/my">Мои посылки</a></li> <li><a href="/contest/1335/status">Статус</a></li> <li><a href="/contest/1335/hacks">Взломы</a></li> <li><a href="/contest/1335/standings">Положение</a></li> <li><a href="/contest/1335/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1e4d40344a82db8876d984e80b212fc7fda414f4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ конфет. Вам хочется распределить все эти $$$n$$$ конфет между сёстрами так, что:</p><ul> <li> Алиса получит $$$a$$$ ($$$a &gt; 0$$$) конфет; </li><li> Бетти получит $$$b$$$ ($$$b &gt; 0$$$) конфет; </li><li> каждая сестра получит некоторое <span class="tex-font-style-bf">целое</span> количество конфет; </li><li> Алиса получит больше конфет, чем Бетти (то есть $$$a &gt; b$$$); </li><li> все конфеты будут отданы одной из двух сестёр (то есть $$$a+b=n$$$). </li></ul><p>Ваша задача — посчитать количество способов распределить $$$n$$$ конфет между девочками так, как описано выше. Учтите, что конфеты неразличимы между собой.</p><p>Формально, найдите количество способов представить $$$n$$$ как сумму $$$n=a+b$$$, где $$$a$$$ и $$$b$$$ — положительные целые числа и $$$a&gt;b$$$.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$) — количество конфет, которое у вас есть.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — количество способов распределить ровно $$$n$$$ конфет между девочками так, как описано в условии задачи. Если не существует способа, удовлетворяющего всем условиям, выведите $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 7 1 2 3 2000000000 763243547 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 0 1 999999999 381621773 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора тестовых данных возможные $$$3$$$ способа распределения конфет — это:</p><ul> <li> $$$a=6$$$, $$$b=1$$$; </li><li> $$$a=5$$$, $$$b=2$$$; </li><li> $$$a=4$$$, $$$b=3$$$. </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 11:00: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:'81249c905b5e3a56',t:'MTY5NjY2NTYzOC42MTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1335B
1335
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$$$, $$$a$$$ и $$$b$$$. Вам хочется построить такую строку $$$s$$$ длины $$$n$$$, состоящую из строчных букв латинского алфавита, что <span class="tex-font-style-bf">каждая подстрока</span> длины $$$a$$$ содержит <span class="tex-font-style-bf">ровно</span> $$$b$$$ различных букв. Гарантируется, что ответ существует.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Напомним, что подстрокой строки $$$s[l \dots r]$$$ называется строка $$$s_l, s_{l+1}, \dots, s_{r}$$$, длина которой равна $$$r - l + 1$$$. В этой задаче вам интересны только подстроки длины $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка каждого набора содержит три разделенных пробелами целых числа $$$n$$$, $$$a$$$ и $$$b$$$ ($$$1 \le a \le n \le 2000, 1 \le b \le \min(26, a)$$$), где $$$n$$$ — длина необходимой строки, $$$a$$$ — длина подстроки, а $$$b$$$ — требуемое количество различных букв в каждой подстроке длины $$$a$$$.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2000$$$ ($$$\sum n \le 2000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — такую строку $$$s$$$ длины $$$n$$$, состоящую из строчных букв латинского алфавита, что <span class="tex-font-style-bf">каждая подстрока</span> длины $$$a$$$ содержит <span class="tex-font-style-bf">ровно</span> $$$b$$$ различных букв. Если ответов несколько, выведите любой из них. Гарантируется, что ответ существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 7 5 3 6 1 1 6 6 1 5 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> tleelte qwerty vvvvvv abcde </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера посмотрим на все подстроки длины $$$5$$$:</p><ul> <li> «<span class="tex-font-style-tt">tleel</span>» — в ней три различных буквы $$$3$$$, </li><li> «<span class="tex-font-style-tt">leelt</span>» — в ней три различных буквы $$$3$$$, </li><li> «<span class="tex-font-style-tt">eelte</span>» — в ней три различных буквы $$$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="4936ecf7833a44abf43f767d35920c28"/> <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="02d43bcc2dd3b25149c439050237c87344017840"/> <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='4936ecf7833a44abf43f767d35920c28'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1335%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='4936ecf7833a44abf43f767d35920c28'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1335">Codeforces Round 634 (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='4936ecf7833a44abf43f767d35920c28'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1335/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='4936ecf7833a44abf43f767d35920c28'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="592972"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4936ecf7833a44abf43f767d35920c28'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="592972"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75908" title="Codeforces Round #634 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10762:10763" 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/75993" title="75993" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10765:10766" 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/1335">Задачи</a></li> <li><a href="/contest/1335/submit">Отослать</a></li> <li><a href="/contest/1335/my">Мои посылки</a></li> <li><a href="/contest/1335/status">Статус</a></li> <li><a href="/contest/1335/hacks">Взломы</a></li> <li><a href="/contest/1335/standings">Положение</a></li> <li><a href="/contest/1335/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_935873211bdc19ac831eb236540cfaa4684e2766"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$, $$$a$$$ и $$$b$$$. Вам хочется построить такую строку $$$s$$$ длины $$$n$$$, состоящую из строчных букв латинского алфавита, что <span class="tex-font-style-bf">каждая подстрока</span> длины $$$a$$$ содержит <span class="tex-font-style-bf">ровно</span> $$$b$$$ различных букв. Гарантируется, что ответ существует.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Напомним, что подстрокой строки $$$s[l \dots r]$$$ называется строка $$$s_l, s_{l+1}, \dots, s_{r}$$$, длина которой равна $$$r - l + 1$$$. В этой задаче вам интересны только подстроки длины $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка каждого набора содержит три разделенных пробелами целых числа $$$n$$$, $$$a$$$ и $$$b$$$ ($$$1 \le a \le n \le 2000, 1 \le b \le \min(26, a)$$$), где $$$n$$$ — длина необходимой строки, $$$a$$$ — длина подстроки, а $$$b$$$ — требуемое количество различных букв в каждой подстроке длины $$$a$$$.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2000$$$ ($$$\sum n \le 2000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — такую строку $$$s$$$ длины $$$n$$$, состоящую из строчных букв латинского алфавита, что <span class="tex-font-style-bf">каждая подстрока</span> длины $$$a$$$ содержит <span class="tex-font-style-bf">ровно</span> $$$b$$$ различных букв. Если ответов несколько, выведите любой из них. Гарантируется, что ответ существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 7 5 3 6 1 1 6 6 1 5 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> tleelte qwerty vvvvvv abcde </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера посмотрим на все подстроки длины $$$5$$$:</p><ul> <li> «<span class="tex-font-style-tt">tleel</span>» — в ней три различных буквы $$$3$$$, </li><li> «<span class="tex-font-style-tt">leelt</span>» — в ней три различных буквы $$$3$$$, </li><li> «<span class="tex-font-style-tt">eelte</span>» — в ней три различных буквы $$$3$$$. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:00: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:'81249c9b2b347b17',t:'MTY5NjY2NTY0MC4zMzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*900"]
1335C
1335
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>, состоящие из некоторого подмножества ваших студентов. У каждого студента есть свой собственный навык, навык $$$i$$$-го студента обозначен числом $$$a_i$$$ (у различных студентов могут быть одинаковые навыки).</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><ul> <li> $$$[1, 2, 3]$$$, $$$[4, 4]$$$ не являются подходящей парой команд, потому что их размеры должны быть одинаковыми; </li><li> $$$[1, 1, 2]$$$, $$$[3, 3, 3]$$$ не являются подходящей парой команд, потому что первая команда не должна включать студентов с одинаковыми навыками; </li><li> $$$[1, 2, 3]$$$, $$$[3, 4, 4]$$$ не являются подходящей парой команд, потому что вторая команда должна включать студентов с одинаковыми навыками; </li><li> $$$[1, 2, 3]$$$, $$$[3, 3, 3]$$$ — подходящая пара команд; </li><li> $$$[5]$$$, $$$[6]$$$ — тоже подходящая пара команд. </li></ul><p>Ваша задача — найти максимально возможный размер команд $$$x$$$, для которого возможно составить подходящую пару команд, где каждая команда имеет размер $$$x$$$ (в первой команде все навыки различны, во второй — все навыки равны между собой). Студент не может входить более чем в одну команду.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество студентов. Вторая строка набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), где $$$a_i$$$ — это навык $$$i$$$-го студента. У различных студентов могут быть одинаковые навыки.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</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 7 4 2 4 1 4 3 4 5 2 1 5 4 3 1 1 4 1 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера возможно составить две команды размера $$$3$$$: первая команда может иметь вид $$$[1, 2, 4]$$$, вторая команда может иметь вид $$$[4, 4, 4]$$$. Заметим, есть и другие способы выбрать две команды размера $$$3$$$, которые соответствуют требованиям выше.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="1d520c3db9c61b8e2b1f60a51987cfd1"/> <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="02d43bcc2dd3b25149c439050237c87344017840"/> <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='1d520c3db9c61b8e2b1f60a51987cfd1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1335%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='1d520c3db9c61b8e2b1f60a51987cfd1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1335">Codeforces Round 634 (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='1d520c3db9c61b8e2b1f60a51987cfd1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1335/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='1d520c3db9c61b8e2b1f60a51987cfd1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="592973"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1d520c3db9c61b8e2b1f60a51987cfd1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="592973"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75908" title="Codeforces Round #634 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10762:10763" 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/75993" title="75993" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10765:10766" 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/1335">Задачи</a></li> <li><a href="/contest/1335/submit">Отослать</a></li> <li><a href="/contest/1335/my">Мои посылки</a></li> <li><a href="/contest/1335/status">Статус</a></li> <li><a href="/contest/1335/hacks">Взломы</a></li> <li><a href="/contest/1335/standings">Положение</a></li> <li><a href="/contest/1335/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_48819d87fc0bd544a2b11af05fcf704c1dda06fe"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>, состоящие из некоторого подмножества ваших студентов. У каждого студента есть свой собственный навык, навык $$$i$$$-го студента обозначен числом $$$a_i$$$ (у различных студентов могут быть одинаковые навыки).</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><ul> <li> $$$[1, 2, 3]$$$, $$$[4, 4]$$$ не являются подходящей парой команд, потому что их размеры должны быть одинаковыми; </li><li> $$$[1, 1, 2]$$$, $$$[3, 3, 3]$$$ не являются подходящей парой команд, потому что первая команда не должна включать студентов с одинаковыми навыками; </li><li> $$$[1, 2, 3]$$$, $$$[3, 4, 4]$$$ не являются подходящей парой команд, потому что вторая команда должна включать студентов с одинаковыми навыками; </li><li> $$$[1, 2, 3]$$$, $$$[3, 3, 3]$$$ — подходящая пара команд; </li><li> $$$[5]$$$, $$$[6]$$$ — тоже подходящая пара команд. </li></ul><p>Ваша задача — найти максимально возможный размер команд $$$x$$$, для которого возможно составить подходящую пару команд, где каждая команда имеет размер $$$x$$$ (в первой команде все навыки различны, во второй — все навыки равны между собой). Студент не может входить более чем в одну команду.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество студентов. Вторая строка набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), где $$$a_i$$$ — это навык $$$i$$$-го студента. У различных студентов могут быть одинаковые навыки.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</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 7 4 2 4 1 4 3 4 5 2 1 5 4 3 1 1 4 1 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера возможно составить две команды размера $$$3$$$: первая команда может иметь вид $$$[1, 2, 4]$$$, вторая команда может иметь вид $$$[4, 4, 4]$$$. Заметим, есть и другие способы выбрать две команды размера $$$3$$$, которые соответствуют требованиям выше.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:00: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:'81249ca3df1d9d63',t:'MTY5NjY2NTY0MS42OTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1100"]
1335D
1335
D
ru
D. Анти-судоку
<div class="problem-statement"><div class="header"><div class="title">D. Анти-судоку</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано корректное решение головоломки судоку. Если вы не знаете, что такое судоку, то вы можете прочитать об этом <a href="http://tiny.cc/o26xmz">здесь</a>.</p><p>Картинка, показывающая корректное решение судоку:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/b80d5452b6026b409a6f8a4abae636177ccdfed7.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Блоки ограничены жирным черным цветом.</p><p>Ваша задача — заменить <span class="tex-font-style-bf">не более</span> $$$9$$$ элементов этого поля (то есть, выбрать некоторые $$$1 \le i, j \le 9$$$ и заменить число в позиции $$$(i, j)$$$ на любое другое число в отрезке $$$[1; 9]$$$), чтобы получить <span class="tex-font-style-bf">анти-судоку</span>. <span class="tex-font-style-bf">Анти-судоку</span> — это поле размера $$$9 \times 9$$$, в котором:</p><ul> <li> Каждое число на этом поле находится в отрезке $$$[1; 9]$$$; </li><li> каждая строка содержит как минимум два одинаковых элемента; </li><li> каждый столбец содержит как минимум два одинаковых элемента; </li><li> каждый блок размера $$$3 \times 3$$$ (о том, что такое блок, вы можете прочитать по ссылке выше) содержит как минимум два одинаковых элемента. </li></ul><p>Гарантируется, что ответ существует.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка тестовых данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор состоит из $$$9$$$ строк, каждая строка состоит из $$$9$$$ символов от $$$1$$$ до $$$9$$$ без пробелов — то есть, представляет собой корректное решение головоломки судоку.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — заданное изначально поле с <span class="tex-font-style-bf">не более, чем</span> $$$9$$$ измененными в нем элементами так, что полученное поле является <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> 1 154873296 386592714 729641835 863725149 975314628 412968357 631457982 598236471 247189563 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 154873396 336592714 729645835 863725145 979314628 412958357 631457992 998236471 247789563 </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="5dab4a50f48bb479eb8f527b4105b342"/> <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="02d43bcc2dd3b25149c439050237c87344017840"/> <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='5dab4a50f48bb479eb8f527b4105b342'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1335%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='5dab4a50f48bb479eb8f527b4105b342'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1335">Codeforces Round 634 (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='5dab4a50f48bb479eb8f527b4105b342'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1335/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='5dab4a50f48bb479eb8f527b4105b342'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="592974"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5dab4a50f48bb479eb8f527b4105b342'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="592974"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75908" title="Codeforces Round #634 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10762:10763" 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/75993" title="75993" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10765:10766" 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/1335">Задачи</a></li> <li><a href="/contest/1335/submit">Отослать</a></li> <li><a href="/contest/1335/my">Мои посылки</a></li> <li><a href="/contest/1335/status">Статус</a></li> <li><a href="/contest/1335/hacks">Взломы</a></li> <li><a href="/contest/1335/standings">Положение</a></li> <li><a href="/contest/1335/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_734f49730858da817775d3b9e02eedf9d8f97de7"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Анти-судоку</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано корректное решение головоломки судоку. Если вы не знаете, что такое судоку, то вы можете прочитать об этом <a href="http://tiny.cc/o26xmz">здесь</a>.</p><p>Картинка, показывающая корректное решение судоку:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/b80d5452b6026b409a6f8a4abae636177ccdfed7.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Блоки ограничены жирным черным цветом.</p><p>Ваша задача — заменить <span class="tex-font-style-bf">не более</span> $$$9$$$ элементов этого поля (то есть, выбрать некоторые $$$1 \le i, j \le 9$$$ и заменить число в позиции $$$(i, j)$$$ на любое другое число в отрезке $$$[1; 9]$$$), чтобы получить <span class="tex-font-style-bf">анти-судоку</span>. <span class="tex-font-style-bf">Анти-судоку</span> — это поле размера $$$9 \times 9$$$, в котором:</p><ul> <li> Каждое число на этом поле находится в отрезке $$$[1; 9]$$$; </li><li> каждая строка содержит как минимум два одинаковых элемента; </li><li> каждый столбец содержит как минимум два одинаковых элемента; </li><li> каждый блок размера $$$3 \times 3$$$ (о том, что такое блок, вы можете прочитать по ссылке выше) содержит как минимум два одинаковых элемента. </li></ul><p>Гарантируется, что ответ существует.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка тестовых данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор состоит из $$$9$$$ строк, каждая строка состоит из $$$9$$$ символов от $$$1$$$ до $$$9$$$ без пробелов — то есть, представляет собой корректное решение головоломки судоку.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — заданное изначально поле с <span class="tex-font-style-bf">не более, чем</span> $$$9$$$ измененными в нем элементами так, что полученное поле является <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> 1 154873296 386592714 729641835 863725149 975314628 412968357 631457982 598236471 247189563 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 154873396 336592714 729645835 863725145 979314628 412958357 631457992 998236471 247789563 </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 11:00: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:'81249cac4acf16af',t:'MTY5NjY2NTY0My4wMjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1300"]
1335E1
1335
E1
ru
E1. Палиндром из трех блоков (простая версия)
<div class="problem-statement"><div class="header"><div class="title">E1. Палиндром из трех блоков (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между простой и сложной версиями — ограничения</span>.</p><p>Вам дана последовательность $$$a$$$, состоящая из $$$n$$$ положительных чисел.</p><p>Определим <span class="tex-font-style-bf">палиндром из трех блоков</span> как последовательность, которая состоит из <span class="tex-font-style-it">не более, чем двух</span> различных элементов (назовем эти элементы $$$a$$$ и $$$b$$$, $$$a$$$ может быть равно $$$b$$$) и выглядит следующим образом $$$[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$$$. Здесь $$$x, y$$$ — числа, большие или равные $$$0$$$. Например, последовательности $$$[]$$$, $$$[2]$$$, $$$[1, 1]$$$, $$$[1, 2, 1]$$$, $$$[1, 2, 2, 1]$$$ и $$$[1, 1, 2, 1, 1]$$$ — <span class="tex-font-style-bf">палиндромы из трех блоков</span>, но $$$[1, 2, 3, 2, 1]$$$, $$$[1, 2, 1, 2, 1]$$$ и $$$[1, 2]$$$ — нет.</p><p>Ваша задача — выбрать максимальную по длине <span class="tex-font-style-bf">подпоследовательность</span> $$$a$$$, которая является <span class="tex-font-style-bf">палиндромом из трех блоков</span>.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Напомним, что последовательность $$$t$$$ является подпоследовательностью последовательности $$$s$$$, если $$$t$$$ может быть получена из $$$s$$$ после удаления нуля или более элементов без изменения порядка оставшихся элементов. Например, если $$$s=[1, 2, 1, 3, 1, 2, 1]$$$, то возможные подпоследовательности: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ и $$$[1, 2, 1, 3, 1, 2, 1]$$$, но не $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2000$$$) — длину $$$a$$$. Вторая строка набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 26$$$), где $$$a_i$$$ — это $$$i$$$-й элемент в $$$a$$$. <span class="tex-font-style-bf">Заметьте, что максимальное значение $$$a_i$$$ может быть до $$$26$$$</span>.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2000$$$ ($$$\sum n \le 2000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — максимально возможную длину некоторой подпоследовательности $$$a$$$, которая является <span class="tex-font-style-bf">палиндромом из трех блоков</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 8 1 1 2 2 3 2 1 1 3 1 3 3 4 1 10 10 1 1 26 2 2 1 3 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 2 4 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="5a12af85c0648d664e594d47d71d3967"/> <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="02d43bcc2dd3b25149c439050237c87344017840"/> <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='5a12af85c0648d664e594d47d71d3967'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1335%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='5a12af85c0648d664e594d47d71d3967'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1335">Codeforces Round 634 (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='5a12af85c0648d664e594d47d71d3967'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1335/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='5a12af85c0648d664e594d47d71d3967'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="592975"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5a12af85c0648d664e594d47d71d3967'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="592975"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75908" title="Codeforces Round #634 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10762:10763" 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/75993" title="75993" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10765:10766" 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/1335">Задачи</a></li> <li><a href="/contest/1335/submit">Отослать</a></li> <li><a href="/contest/1335/my">Мои посылки</a></li> <li><a href="/contest/1335/status">Статус</a></li> <li><a href="/contest/1335/hacks">Взломы</a></li> <li><a href="/contest/1335/standings">Положение</a></li> <li><a href="/contest/1335/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_40a194a7bf9bd7dfee80a03e6cb9f3ee8055a43f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E1. Палиндром из трех блоков (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между простой и сложной версиями — ограничения</span>.</p><p>Вам дана последовательность $$$a$$$, состоящая из $$$n$$$ положительных чисел.</p><p>Определим <span class="tex-font-style-bf">палиндром из трех блоков</span> как последовательность, которая состоит из <span class="tex-font-style-it">не более, чем двух</span> различных элементов (назовем эти элементы $$$a$$$ и $$$b$$$, $$$a$$$ может быть равно $$$b$$$) и выглядит следующим образом $$$[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$$$. Здесь $$$x, y$$$ — числа, большие или равные $$$0$$$. Например, последовательности $$$[]$$$, $$$[2]$$$, $$$[1, 1]$$$, $$$[1, 2, 1]$$$, $$$[1, 2, 2, 1]$$$ и $$$[1, 1, 2, 1, 1]$$$ — <span class="tex-font-style-bf">палиндромы из трех блоков</span>, но $$$[1, 2, 3, 2, 1]$$$, $$$[1, 2, 1, 2, 1]$$$ и $$$[1, 2]$$$ — нет.</p><p>Ваша задача — выбрать максимальную по длине <span class="tex-font-style-bf">подпоследовательность</span> $$$a$$$, которая является <span class="tex-font-style-bf">палиндромом из трех блоков</span>.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Напомним, что последовательность $$$t$$$ является подпоследовательностью последовательности $$$s$$$, если $$$t$$$ может быть получена из $$$s$$$ после удаления нуля или более элементов без изменения порядка оставшихся элементов. Например, если $$$s=[1, 2, 1, 3, 1, 2, 1]$$$, то возможные подпоследовательности: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ и $$$[1, 2, 1, 3, 1, 2, 1]$$$, но не $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2000$$$) — длину $$$a$$$. Вторая строка набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 26$$$), где $$$a_i$$$ — это $$$i$$$-й элемент в $$$a$$$. <span class="tex-font-style-bf">Заметьте, что максимальное значение $$$a_i$$$ может быть до $$$26$$$</span>.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2000$$$ ($$$\sum n \le 2000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — максимально возможную длину некоторой подпоследовательности $$$a$$$, которая является <span class="tex-font-style-bf">палиндромом из трех блоков</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 8 1 1 2 2 3 2 1 1 3 1 3 3 4 1 10 10 1 1 26 2 2 1 3 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 2 4 1 1 3 </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 11:00: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:'81249cb49a8313c6',t:'MTY5NjY2NTY0NC41MTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1700"]
1335E2
1335
E2
ru
E2. Палиндром из трех блоков (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">E2. Палиндром из трех блоков (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между простой и сложной версиями — ограничения</span>.</p><p>Вам дана последовательность $$$a$$$, состоящая из $$$n$$$ положительных чисел.</p><p>Определим <span class="tex-font-style-bf">палиндром из трех блоков</span> как последовательность, которая состоит из <span class="tex-font-style-it">не более, чем двух</span> различных элементов (назовем эти элементы $$$a$$$ и $$$b$$$, $$$a$$$ может быть равно $$$b$$$) и выглядит следующим образом $$$[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$$$. Здесь $$$x, y$$$ — числа, большие или равные $$$0$$$. Например, последовательности $$$[]$$$, $$$[2]$$$, $$$[1, 1]$$$, $$$[1, 2, 1]$$$, $$$[1, 2, 2, 1]$$$ and $$$[1, 1, 2, 1, 1]$$$ — <span class="tex-font-style-bf">палиндромы из трех блоков</span>, но $$$[1, 2, 3, 2, 1]$$$, $$$[1, 2, 1, 2, 1]$$$ и $$$[1, 2]$$$ — нет.</p><p>Ваша задача — выбрать максимальную по длине <span class="tex-font-style-bf">подпоследовательность</span> $$$a$$$, которая является <span class="tex-font-style-bf">палиндромом из трех блоков</span>.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Напомним, что последовательность $$$t$$$ является подпоследовательностью последовательности $$$s$$$, если $$$t$$$ может быть получена из $$$s$$$ после удаления нуля или более элементов без изменения порядка оставшихся элементов. Например, если $$$s=[1, 2, 1, 3, 1, 2, 1]$$$, то возможные подпоследовательности: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ и $$$[1, 2, 1, 3, 1, 2, 1]$$$, но не $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длину $$$a$$$. Вторая строка набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 200$$$), где $$$a_i$$$ — это $$$i$$$-й элемент в $$$a$$$. <span class="tex-font-style-bf">Заметьте, что максимальное значение $$$a_i$$$ может быть до $$$200$$$</span>.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — максимально возможную длину некоторой подпоследовательности $$$a$$$, которая является <span class="tex-font-style-bf">палиндромом из трех блоков</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 8 1 1 2 2 3 2 1 1 3 1 3 3 4 1 10 10 1 1 26 2 2 1 3 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 2 4 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="05498d7f0d9de1b09abf93ba219ff470"/> <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="02d43bcc2dd3b25149c439050237c87344017840"/> <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='05498d7f0d9de1b09abf93ba219ff470'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1335%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='05498d7f0d9de1b09abf93ba219ff470'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1335">Codeforces Round 634 (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='05498d7f0d9de1b09abf93ba219ff470'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1335/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='05498d7f0d9de1b09abf93ba219ff470'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="592976"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='05498d7f0d9de1b09abf93ba219ff470'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="592976"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75908" title="Codeforces Round #634 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10762:10763" 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/75993" title="75993" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10765:10766" 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/1335">Задачи</a></li> <li><a href="/contest/1335/submit">Отослать</a></li> <li><a href="/contest/1335/my">Мои посылки</a></li> <li><a href="/contest/1335/status">Статус</a></li> <li><a href="/contest/1335/hacks">Взломы</a></li> <li><a href="/contest/1335/standings">Положение</a></li> <li><a href="/contest/1335/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a00bf004ddd99be99c091e554752d5ec9dc95ebc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E2. Палиндром из трех блоков (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между простой и сложной версиями — ограничения</span>.</p><p>Вам дана последовательность $$$a$$$, состоящая из $$$n$$$ положительных чисел.</p><p>Определим <span class="tex-font-style-bf">палиндром из трех блоков</span> как последовательность, которая состоит из <span class="tex-font-style-it">не более, чем двух</span> различных элементов (назовем эти элементы $$$a$$$ и $$$b$$$, $$$a$$$ может быть равно $$$b$$$) и выглядит следующим образом $$$[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$$$. Здесь $$$x, y$$$ — числа, большие или равные $$$0$$$. Например, последовательности $$$[]$$$, $$$[2]$$$, $$$[1, 1]$$$, $$$[1, 2, 1]$$$, $$$[1, 2, 2, 1]$$$ and $$$[1, 1, 2, 1, 1]$$$ — <span class="tex-font-style-bf">палиндромы из трех блоков</span>, но $$$[1, 2, 3, 2, 1]$$$, $$$[1, 2, 1, 2, 1]$$$ и $$$[1, 2]$$$ — нет.</p><p>Ваша задача — выбрать максимальную по длине <span class="tex-font-style-bf">подпоследовательность</span> $$$a$$$, которая является <span class="tex-font-style-bf">палиндромом из трех блоков</span>.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Напомним, что последовательность $$$t$$$ является подпоследовательностью последовательности $$$s$$$, если $$$t$$$ может быть получена из $$$s$$$ после удаления нуля или более элементов без изменения порядка оставшихся элементов. Например, если $$$s=[1, 2, 1, 3, 1, 2, 1]$$$, то возможные подпоследовательности: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ и $$$[1, 2, 1, 3, 1, 2, 1]$$$, но не $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длину $$$a$$$. Вторая строка набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 200$$$), где $$$a_i$$$ — это $$$i$$$-й элемент в $$$a$$$. <span class="tex-font-style-bf">Заметьте, что максимальное значение $$$a_i$$$ может быть до $$$200$$$</span>.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — максимально возможную длину некоторой подпоследовательности $$$a$$$, которая является <span class="tex-font-style-bf">палиндромом из трех блоков</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 8 1 1 2 2 3 2 1 1 3 1 3 3 4 1 10 10 1 1 26 2 2 1 3 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 2 4 1 1 3 </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 11:00:45</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:'81249cbdeb3503dd',t:'MTY5NjY2NTY0NS44OTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1800"]
1335F
1335
F
ru
F. Роботы на поле
<div class="problem-statement"><div class="header"><div class="title">F. Роботы на поле</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Задано прямоугольное поле размера $$$n \times m$$$. Каждая клетка поля покрашена либо в черный цвет ('<span class="tex-font-style-tt">0</span>'), либо в белый цвет ('<span class="tex-font-style-tt">1</span>'). Цвет клетки $$$(i, j)$$$ обозначается как $$$c_{i, j}$$$. Вам также задана карта направлений: для каждой клетки указано направление $$$s_{i, j}$$$, которое равно одному из четырех символов '<span class="tex-font-style-tt">U</span>', '<span class="tex-font-style-tt">R</span>', '<span class="tex-font-style-tt">D</span>' и '<span class="tex-font-style-tt">L</span>'.</p><ul> <li> Если $$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">U</span>', то из клетки $$$(i, j)$$$ есть переход в клетку $$$(i - 1, j)$$$; </li><li> если $$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">R</span>', то из клетки $$$(i, j)$$$ есть переход в клетку $$$(i, j + 1)$$$; </li><li> если $$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">D</span>', то из клетки $$$(i, j)$$$ есть переход в клетку $$$(i + 1, j)$$$; </li><li> если $$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">L</span>', то из клетки $$$(i, j)$$$ есть переход в клетку $$$(i, j - 1)$$$. </li></ul><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>Вы хотите поставить роботов на поле (не более одного робота в клетку). При этом следующие условия должны быть соблюдены.</p><ul> <li> Во-первых, каждый робот <span class="tex-font-style-bf">всегда обязан перемещаться</span> (то есть он не может пропустить ход). <span class="tex-font-style-bf">За один ход каждый робот перемещается в соседнюю клетку в соответствии с текущим направлением</span>. </li><li> Во-вторых, вам необходимо поставить роботов таким образом, что <span class="tex-font-style-bf">не найдется такого хода</span>, перед которым два различных робота стоят в одной и той же клетке (это также значит, что вы не можете поставить двух роботов в одну и ту же клетку). Таким образом, Если поле равно «<span class="tex-font-style-tt">RL</span>» (одна строка, два столбца, цвета здесь не важны), то вы можете поставить двух роботов в клетки $$$(1, 1)$$$ и $$$(1, 2)$$$, но если поле равно «<span class="tex-font-style-tt">RLL</span>», то вы не можете поставить роботов в клетки $$$(1, 1)$$$ и $$$(1, 3)$$$, потому что в течение первой секунды оба робота будут стоять в клетке $$$(1, 2)$$$. </li></ul><p>Роботы делают бесконечное количество ходов.</p><p>Ваша задача — поставить максимальное количество роботов таким образом, чтобы удовлетворить все условия, описанные выше, а среди всех таких способов вам необходимо выбрать такой, что количество <span class="tex-font-style-bf">черных</span> клеток, на которых стоят роботы <span class="tex-font-style-bf">перед началом всех перемещений</span> является максимально возможным. <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$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 &lt; nm \le 10^6$$$) — количество строк и количество столбцов соответственно.</p><p>Следующие $$$n$$$ строк содержат по $$$m$$$ символов каждая, где $$$j$$$-й символ $$$i$$$-й строки равен $$$c_{i, j}$$$ ($$$c_{i, j}$$$ равно либо '<span class="tex-font-style-tt">0</span>', если клетка $$$(i, j)$$$ покрашена в черный цвет, либо '<span class="tex-font-style-tt">1</span>', если клетка $$$(i, j)$$$ покрашена в белый цвет).</p><p>Следующие $$$n$$$ строк также содержат по $$$m$$$ символов каждая, где $$$j$$$-й символ $$$i$$$-й строки равен $$$s_{i, j}$$$ ($$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">U</span>', '<span class="tex-font-style-tt">R</span>', '<span class="tex-font-style-tt">D</span>' или '<span class="tex-font-style-tt">L</span>', и описывает направление клетки $$$(i, j)$$$).</p><p>Гарантируется, что сумма размеров полей не превосходит $$$10^6$$$ ($$$\sum nm \le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите два числа — максимальное количество роботов, которое вы можете поставить, чтобы удовлетворить все ограничения, указанные в условии задачи, и максимальное количество <span class="tex-font-style-bf">черных</span> клеток, в которых находятся роботы <span class="tex-font-style-bf">перед началом всех перемещений</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> 3 1 2 01 RL 3 3 001 101 110 RLL DLD ULL 3 3 000 000 000 RRD RLD ULL </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 4 3 2 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="0152d8d2e189b7268add7aa5f83445e0"/> <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="02d43bcc2dd3b25149c439050237c87344017840"/> <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='0152d8d2e189b7268add7aa5f83445e0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1335%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='0152d8d2e189b7268add7aa5f83445e0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1335">Codeforces Round 634 (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='0152d8d2e189b7268add7aa5f83445e0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1335/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Произведение матриц, определитель, правило Крамера, системы линейных уравнений"> матрицы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='0152d8d2e189b7268add7aa5f83445e0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="592977"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0152d8d2e189b7268add7aa5f83445e0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="592977"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75908" title="Codeforces Round #634 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10762:10763" 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/75993" title="75993" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10765:10766" 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/1335">Задачи</a></li> <li><a href="/contest/1335/submit">Отослать</a></li> <li><a href="/contest/1335/my">Мои посылки</a></li> <li><a href="/contest/1335/status">Статус</a></li> <li><a href="/contest/1335/hacks">Взломы</a></li> <li><a href="/contest/1335/standings">Положение</a></li> <li><a href="/contest/1335/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c442372d660355a5805ec21e264c43895123bd46"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Роботы на поле</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Задано прямоугольное поле размера $$$n \times m$$$. Каждая клетка поля покрашена либо в черный цвет ('<span class="tex-font-style-tt">0</span>'), либо в белый цвет ('<span class="tex-font-style-tt">1</span>'). Цвет клетки $$$(i, j)$$$ обозначается как $$$c_{i, j}$$$. Вам также задана карта направлений: для каждой клетки указано направление $$$s_{i, j}$$$, которое равно одному из четырех символов '<span class="tex-font-style-tt">U</span>', '<span class="tex-font-style-tt">R</span>', '<span class="tex-font-style-tt">D</span>' и '<span class="tex-font-style-tt">L</span>'.</p><ul> <li> Если $$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">U</span>', то из клетки $$$(i, j)$$$ есть переход в клетку $$$(i - 1, j)$$$; </li><li> если $$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">R</span>', то из клетки $$$(i, j)$$$ есть переход в клетку $$$(i, j + 1)$$$; </li><li> если $$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">D</span>', то из клетки $$$(i, j)$$$ есть переход в клетку $$$(i + 1, j)$$$; </li><li> если $$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">L</span>', то из клетки $$$(i, j)$$$ есть переход в клетку $$$(i, j - 1)$$$. </li></ul><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>Вы хотите поставить роботов на поле (не более одного робота в клетку). При этом следующие условия должны быть соблюдены.</p><ul> <li> Во-первых, каждый робот <span class="tex-font-style-bf">всегда обязан перемещаться</span> (то есть он не может пропустить ход). <span class="tex-font-style-bf">За один ход каждый робот перемещается в соседнюю клетку в соответствии с текущим направлением</span>. </li><li> Во-вторых, вам необходимо поставить роботов таким образом, что <span class="tex-font-style-bf">не найдется такого хода</span>, перед которым два различных робота стоят в одной и той же клетке (это также значит, что вы не можете поставить двух роботов в одну и ту же клетку). Таким образом, Если поле равно «<span class="tex-font-style-tt">RL</span>» (одна строка, два столбца, цвета здесь не важны), то вы можете поставить двух роботов в клетки $$$(1, 1)$$$ и $$$(1, 2)$$$, но если поле равно «<span class="tex-font-style-tt">RLL</span>», то вы не можете поставить роботов в клетки $$$(1, 1)$$$ и $$$(1, 3)$$$, потому что в течение первой секунды оба робота будут стоять в клетке $$$(1, 2)$$$. </li></ul><p>Роботы делают бесконечное количество ходов.</p><p>Ваша задача — поставить максимальное количество роботов таким образом, чтобы удовлетворить все условия, описанные выше, а среди всех таких способов вам необходимо выбрать такой, что количество <span class="tex-font-style-bf">черных</span> клеток, на которых стоят роботы <span class="tex-font-style-bf">перед началом всех перемещений</span> является максимально возможным. <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$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 &lt; nm \le 10^6$$$) — количество строк и количество столбцов соответственно.</p><p>Следующие $$$n$$$ строк содержат по $$$m$$$ символов каждая, где $$$j$$$-й символ $$$i$$$-й строки равен $$$c_{i, j}$$$ ($$$c_{i, j}$$$ равно либо '<span class="tex-font-style-tt">0</span>', если клетка $$$(i, j)$$$ покрашена в черный цвет, либо '<span class="tex-font-style-tt">1</span>', если клетка $$$(i, j)$$$ покрашена в белый цвет).</p><p>Следующие $$$n$$$ строк также содержат по $$$m$$$ символов каждая, где $$$j$$$-й символ $$$i$$$-й строки равен $$$s_{i, j}$$$ ($$$s_{i, j}$$$ равно '<span class="tex-font-style-tt">U</span>', '<span class="tex-font-style-tt">R</span>', '<span class="tex-font-style-tt">D</span>' или '<span class="tex-font-style-tt">L</span>', и описывает направление клетки $$$(i, j)$$$).</p><p>Гарантируется, что сумма размеров полей не превосходит $$$10^6$$$ ($$$\sum nm \le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите два числа — максимальное количество роботов, которое вы можете поставить, чтобы удовлетворить все ограничения, указанные в условии задачи, и максимальное количество <span class="tex-font-style-bf">черных</span> клеток, в которых находятся роботы <span class="tex-font-style-bf">перед началом всех перемещений</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> 3 1 2 01 RL 3 3 001 101 110 RLL DLD ULL 3 3 000 000 000 RRD RLD ULL </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 4 3 2 2 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:00: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:'81249cc699399d73',t:'MTY5NjY2NTY0Ny4yODEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043d\u043c", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2200"]
1336A
1336
A
ru
A. Linova и королевство
<div class="problem-statement"><div class="header"><div class="title">A. Linova и королевство</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Написание легких романов является очень важной частью жизни Linova. Прошлой ночью ей приснилось сказочное королевство. Linova написала легкий роман про это королевство, как только проснулась. Конечно, она стала его королевой.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/df63f4ac458c231c1258e895434dcb4c2f090f09.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>Всего есть $$$n$$$ городов и $$$n-1$$$ двусторонняя дорога, соединяющая некоторые пары городов королевства. Из любого города вы можете попасть в любой другой город, пройдя по некоторым дорогам. Города пронумерованы от $$$1$$$ до $$$n$$$ и город $$$1$$$ является столицей королевства. Таким образом, структура королевства является деревом.</p><p>Как королева, Linova планирует выбрать <span class="tex-font-style-bf">ровно</span> $$$k$$$ городов для развития индустрии, тогда как в остальных городах будет развиваться туризм. Столица также может быть как индустриальным, так и туристическим городом.</p><p>Раз в год в столице будет проходить встреча. Для участия во встрече, каждый <span class="tex-font-style-bf">индустриальный город</span> посылает участника. Все посланники приедут в столицу по кратчайшему пути (который как известно единственный в дереве).</p><p>Путешествие по туристическим городам очень приятно. Для каждого посланника, его <span class="tex-font-style-it">уровень счастья</span> равен количеству <span class="tex-font-style-bf">туристических городов</span> на его пути.</p><p>Для того, чтобы люди любили королеву, Linova хочет выбрать $$$k$$$ городов так, чтобы максимизировать сумму <span class="tex-font-style-it">уровней счастья</span> всех посланников. Можете ли вы посчитать максимальную возможную сумму для нее?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k&lt; n$$$)  — количество городов и индустриальных городов, соответственно.</p><p>Каждая из следующих $$$n-1$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1\le u,v\le n$$$), обозначающих наличие дороги, соединяющей города $$$u$$$ и $$$v$$$.</p><p>Гарантируется, что из любого города можно достичь любой другой по дорогам.</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> 7 4 1 2 1 3 1 4 3 5 3 6 4 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 1 2 1 3 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 5 7 5 1 7 6 1 3 7 8 3 2 1 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><img class="tex-graphics" src="https://espresso.codeforces.com/d811810ac8e2c43cb201a3388ae50f1b3e17a687.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>В первом тесте, Linova может выбрать города $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ для развития индустрии, тогда <span class="tex-font-style-it">уровень счастья</span> посланника из города $$$2$$$ будет равен $$$1$$$, <span class="tex-font-style-it">уровни счастья</span> посланников из городов $$$5$$$, $$$6$$$, $$$7$$$ будут равны $$$2$$$. Таким образом, сумма <span class="tex-font-style-it">уровней счастья</span> будет равна $$$7$$$ и можно доказать, что это максимальная возможная сумма, которая может быть.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/3ffb39c877eca7565234f5b27836c176c6a85f3f.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Во втором тесте, выбрав города $$$3$$$ и $$$4$$$ для развития индустрии можно достичь суммы $$$3$$$, но обратите внимание, что Linova планирует выбрать <span class="tex-font-style-bf">ровно</span> $$$k$$$ городов для развития индустрии, поэтому максимальная сумма равна $$$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="3339b249d18d61f2aff57c4d84d5f431"/> <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="a3e2a90714a5b9585ccdbcb93d817b980a2e6bb7"/> <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='3339b249d18d61f2aff57c4d84d5f431'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1336%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='3339b249d18d61f2aff57c4d84d5f431'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1336">Codeforces Round 635 (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='3339b249d18d61f2aff57c4d84d5f431'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1336/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='3339b249d18d61f2aff57c4d84d5f431'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594561"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3339b249d18d61f2aff57c4d84d5f431'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594561"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Codeforces Round #635" target="_blank">Codeforces Round #635 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10768" resourceName="Codeforces Round #635" resourceManual="true" src="//codeforces.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/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10772" resourceName="Codeforces Round #635 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/1336">Задачи</a></li> <li><a href="/contest/1336/submit">Отослать</a></li> <li><a href="/contest/1336/my">Мои посылки</a></li> <li><a href="/contest/1336/status">Статус</a></li> <li><a href="/contest/1336/hacks">Взломы</a></li> <li><a href="/contest/1336/room/1">Комната</a></li> <li><a href="/contest/1336/standings">Положение</a></li> <li><a href="/contest/1336/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b60be8945b4ff7d5dc596838c8cdd253c2f64eda"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Linova и королевство</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Написание легких романов является очень важной частью жизни Linova. Прошлой ночью ей приснилось сказочное королевство. Linova написала легкий роман про это королевство, как только проснулась. Конечно, она стала его королевой.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/df63f4ac458c231c1258e895434dcb4c2f090f09.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>Всего есть $$$n$$$ городов и $$$n-1$$$ двусторонняя дорога, соединяющая некоторые пары городов королевства. Из любого города вы можете попасть в любой другой город, пройдя по некоторым дорогам. Города пронумерованы от $$$1$$$ до $$$n$$$ и город $$$1$$$ является столицей королевства. Таким образом, структура королевства является деревом.</p><p>Как королева, Linova планирует выбрать <span class="tex-font-style-bf">ровно</span> $$$k$$$ городов для развития индустрии, тогда как в остальных городах будет развиваться туризм. Столица также может быть как индустриальным, так и туристическим городом.</p><p>Раз в год в столице будет проходить встреча. Для участия во встрече, каждый <span class="tex-font-style-bf">индустриальный город</span> посылает участника. Все посланники приедут в столицу по кратчайшему пути (который как известно единственный в дереве).</p><p>Путешествие по туристическим городам очень приятно. Для каждого посланника, его <span class="tex-font-style-it">уровень счастья</span> равен количеству <span class="tex-font-style-bf">туристических городов</span> на его пути.</p><p>Для того, чтобы люди любили королеву, Linova хочет выбрать $$$k$$$ городов так, чтобы максимизировать сумму <span class="tex-font-style-it">уровней счастья</span> всех посланников. Можете ли вы посчитать максимальную возможную сумму для нее?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k&lt; n$$$)  — количество городов и индустриальных городов, соответственно.</p><p>Каждая из следующих $$$n-1$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1\le u,v\le n$$$), обозначающих наличие дороги, соединяющей города $$$u$$$ и $$$v$$$.</p><p>Гарантируется, что из любого города можно достичь любой другой по дорогам.</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> 7 4 1 2 1 3 1 4 3 5 3 6 4 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 1 2 1 3 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 5 7 5 1 7 6 1 3 7 8 3 2 1 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><img class="tex-graphics" src="https://espresso.codeforces.com/d811810ac8e2c43cb201a3388ae50f1b3e17a687.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>В первом тесте, Linova может выбрать города $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ для развития индустрии, тогда <span class="tex-font-style-it">уровень счастья</span> посланника из города $$$2$$$ будет равен $$$1$$$, <span class="tex-font-style-it">уровни счастья</span> посланников из городов $$$5$$$, $$$6$$$, $$$7$$$ будут равны $$$2$$$. Таким образом, сумма <span class="tex-font-style-it">уровней счастья</span> будет равна $$$7$$$ и можно доказать, что это максимальная возможная сумма, которая может быть.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/3ffb39c877eca7565234f5b27836c176c6a85f3f.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Во втором тесте, выбрав города $$$3$$$ и $$$4$$$ для развития индустрии можно достичь суммы $$$3$$$, но обратите внимание, что Linova планирует выбрать <span class="tex-font-style-bf">ровно</span> $$$k$$$ городов для развития индустрии, поэтому максимальная сумма равна $$$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 11:00: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:'81249ccf280e03dd',t:'MTY5NjY2NTY0OC42OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1600"]
1336B
1336
B
ru
B. Xenia и разноцветные камушки
<div class="problem-statement"><div class="header"><div class="title">B. Xenia и разноцветные камушки</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>Xenia девочка, рожденная дворянкой. От скуки и одиночества, Xenia вынуждена сама искать какие-то способы развлечься.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/f3da718b55ccc1ed3494e6615f1db496fd70b0ad.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>Недавно Xenia купила $$$n_r$$$ красных камушков, $$$n_g$$$ зеленых камушков и $$$n_b$$$ голубых камушков. Каждый камушек имеет некоторый вес.</p><p>Сейчас она хочет выбрать три камушка.</p><p>Xenia любит разноцветные вещи, поэтому она выберет ровно один камушек каждого цвета.</p><p>Xenia любит баланс, поэтому она хочет выбрать камушки с как можно меньшей разнице в весе.</p><p>Более точно, если положить веса выбранных камушков за $$$x$$$, $$$y$$$ и $$$z$$$, Xenia хочет выбрать камушки, так, чтобы значение $$$(x-y)^2+(y-z)^2+(z-x)^2$$$ было как можно меньше. Как ее лучший друг, можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t \le 100$$$)  — количество тестовых случаев. Затем следует описание $$$t$$$ тестовых случаев.</p><p>Первая строка описания каждого тестового случая содержит три целых числа $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — количество красных камушков, зеленых камушков и голубых камушков, соответственно.</p><p>Вторая строка описания каждого тестового случая содержит $$$n_r$$$ целых чисел $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ равно весу $$$i$$$-о красного камушка.</p><p>Третья строка описания каждого тестового случая содержит $$$n_g$$$ целых чисел $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ равно весу $$$i$$$-о зеленого камушка.</p><p>Четвертая строка описания каждого тестового случая содержит $$$n_b$$$ целых чисел $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ равно весу $$$i$$$-о голубого камушка.</p><p>Гарантируется, что $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (сумма берется по всем тестовым случаям).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите целое число  — минимальное возможное значение, которое Xenia может получить.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14 1999999996000000002 24 24 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, Xenia купила следующие камушки:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/7e400036e7fb1bb1013d79825f1eb0157cb807e7.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Если она возьмет красный камушек с весом $$$7$$$, зеленый камушек с весом $$$6$$$ и голубой камушек с весом $$$4$$$, она получит самый сбалансированный выбор со значением $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="87cccfb0b371cbc744a6066e3e175a69"/> <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="a3e2a90714a5b9585ccdbcb93d817b980a2e6bb7"/> <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='87cccfb0b371cbc744a6066e3e175a69'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1336%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='87cccfb0b371cbc744a6066e3e175a69'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1336">Codeforces Round 635 (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='87cccfb0b371cbc744a6066e3e175a69'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1336/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='87cccfb0b371cbc744a6066e3e175a69'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594566"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='87cccfb0b371cbc744a6066e3e175a69'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594566"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Codeforces Round #635" target="_blank">Codeforces Round #635 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10768" resourceName="Codeforces Round #635" resourceManual="true" src="//codeforces.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/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10772" resourceName="Codeforces Round #635 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/1336">Задачи</a></li> <li><a href="/contest/1336/submit">Отослать</a></li> <li><a href="/contest/1336/my">Мои посылки</a></li> <li><a href="/contest/1336/status">Статус</a></li> <li><a href="/contest/1336/hacks">Взломы</a></li> <li><a href="/contest/1336/room/1">Комната</a></li> <li><a href="/contest/1336/standings">Положение</a></li> <li><a href="/contest/1336/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_41d422fd0f3a2f6bd18dd5711d7bcce4d53bd8bc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Xenia и разноцветные камушки</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>Xenia девочка, рожденная дворянкой. От скуки и одиночества, Xenia вынуждена сама искать какие-то способы развлечься.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/f3da718b55ccc1ed3494e6615f1db496fd70b0ad.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>Недавно Xenia купила $$$n_r$$$ красных камушков, $$$n_g$$$ зеленых камушков и $$$n_b$$$ голубых камушков. Каждый камушек имеет некоторый вес.</p><p>Сейчас она хочет выбрать три камушка.</p><p>Xenia любит разноцветные вещи, поэтому она выберет ровно один камушек каждого цвета.</p><p>Xenia любит баланс, поэтому она хочет выбрать камушки с как можно меньшей разнице в весе.</p><p>Более точно, если положить веса выбранных камушков за $$$x$$$, $$$y$$$ и $$$z$$$, Xenia хочет выбрать камушки, так, чтобы значение $$$(x-y)^2+(y-z)^2+(z-x)^2$$$ было как можно меньше. Как ее лучший друг, можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t \le 100$$$)  — количество тестовых случаев. Затем следует описание $$$t$$$ тестовых случаев.</p><p>Первая строка описания каждого тестового случая содержит три целых числа $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — количество красных камушков, зеленых камушков и голубых камушков, соответственно.</p><p>Вторая строка описания каждого тестового случая содержит $$$n_r$$$ целых чисел $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ равно весу $$$i$$$-о красного камушка.</p><p>Третья строка описания каждого тестового случая содержит $$$n_g$$$ целых чисел $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ равно весу $$$i$$$-о зеленого камушка.</p><p>Четвертая строка описания каждого тестового случая содержит $$$n_b$$$ целых чисел $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ равно весу $$$i$$$-о голубого камушка.</p><p>Гарантируется, что $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (сумма берется по всем тестовым случаям).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите целое число  — минимальное возможное значение, которое Xenia может получить.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14 1999999996000000002 24 24 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, Xenia купила следующие камушки:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/7e400036e7fb1bb1013d79825f1eb0157cb807e7.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Если она возьмет красный камушек с весом $$$7$$$, зеленый камушек с весом $$$6$$$ и голубой камушек с весом $$$4$$$, она получит самый сбалансированный выбор со значением $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.</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 11:00: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:'81249cd80818498d',t:'MTY5NjY2NTY1MC4xOTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1700"]
1336C
1336
C
ru
C. Kaavi и магическое заклинание
<div class="problem-statement"><div class="header"><div class="title">C. Kaavi и магическое заклинание</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Kaavi, таинственная гадалка, глубоко верит в то, что судьба человека неизбежна и неотвратима. Конечно, она зарабатывает себе на жизнь предсказывая будущее других людей. Занимаясь гаданием, Kaavi верит, что магические заклинания могут дать ей огромную силу видеть будущее.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/e031f1a741db6090fee9d6722704d37d130f468e.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>У Kaavi есть строка $$$T$$$ длины $$$m$$$ и все строки, имеющие префикс $$$T$$$ это магические заклинания. У Kaavi также есть строка $$$S$$$ длины $$$n$$$ и пустая строка $$$A$$$.</p><p>Во время гадания, Kaavi нужно применить некоторую последовательность операций. Есть две различные операции:</p><ul><li> Удалить первый символ строки $$$S$$$ и добавить его <span class="tex-font-style-bf">в начало</span> строки $$$A$$$.</li><li> Удалить первый символ строки $$$S$$$ и добавить его <span class="tex-font-style-bf">в конец</span> строки $$$A$$$.</li></ul><p>Kaavi может сделать <span class="tex-font-style-bf">не более, чем</span> $$$n$$$ операций. Для того, чтобы завершить гадание, она хочет узнать количество различных последовательностей операций, для того, чтобы сделать $$$A$$$ магическим заклинанием (то есть эта строка имеет префикс $$$T$$$). Как ее ассистент, можете ли вы помочь ей? Поскольку ответ может быть очень большим, Kaavi хочет знать его остаток при делении на $$$998\,244\,353$$$.</p><p>Две последовательности операций считаются различными, если они различаются по длине или существует такое $$$i$$$, что их $$$i$$$-е операции различаются.</p><p>Подстрокой называется некоторая последовательность последовательных символов строки. Префиксом строки $$$S$$$ называется подстрока $$$S$$$, которая начинается в начале строки $$$S$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится строка $$$S$$$ длины $$$n$$$ ($$$1 \leq n \leq 3000$$$).</p><p>Во второй строке находится строка $$$T$$$ длины $$$m$$$ ($$$1 \leq m \leq n$$$).</p><p>Обе строки состоят только из строчных латинских символов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число  — ответ на задачу по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> abab ba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12</pre></div><div class="input"><div class="title">Входные данные</div><pre> defineintlonglong signedmain </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0</pre></div><div class="input"><div class="title">Входные данные</div><pre> rotator rotator </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4</pre></div><div class="input"><div class="title">Входные данные</div><pre> cacdcdbbbb bdcaccdbbb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/59b1aeccd6c5b78703012f04c99eb547b718f003.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Красные строки это магические заклинания. В первой операции, Kaavi может добавить символ «<span class="tex-font-style-tt">a</span>» в начало или в конец $$$A$$$. Хотя в обоих случаях результат будет одинаковым, это две разные операции. Поэтому ответ $$$6\times2=12$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4c24f6a20c817fb43cd06a908bcfc708"/> <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="a3e2a90714a5b9585ccdbcb93d817b980a2e6bb7"/> <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='4c24f6a20c817fb43cd06a908bcfc708'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1336%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='4c24f6a20c817fb43cd06a908bcfc708'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1336">Codeforces Round 635 (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='4c24f6a20c817fb43cd06a908bcfc708'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1336/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2200 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4c24f6a20c817fb43cd06a908bcfc708'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594567"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4c24f6a20c817fb43cd06a908bcfc708'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594567"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Codeforces Round #635" target="_blank">Codeforces Round #635 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10768" resourceName="Codeforces Round #635" resourceManual="true" src="//codeforces.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/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10772" resourceName="Codeforces Round #635 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/1336">Задачи</a></li> <li><a href="/contest/1336/submit">Отослать</a></li> <li><a href="/contest/1336/my">Мои посылки</a></li> <li><a href="/contest/1336/status">Статус</a></li> <li><a href="/contest/1336/hacks">Взломы</a></li> <li><a href="/contest/1336/room/1">Комната</a></li> <li><a href="/contest/1336/standings">Положение</a></li> <li><a href="/contest/1336/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_54205c7ae09f5580cce7026e1c39a44348324c86"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Kaavi и магическое заклинание</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Kaavi, таинственная гадалка, глубоко верит в то, что судьба человека неизбежна и неотвратима. Конечно, она зарабатывает себе на жизнь предсказывая будущее других людей. Занимаясь гаданием, Kaavi верит, что магические заклинания могут дать ей огромную силу видеть будущее.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/e031f1a741db6090fee9d6722704d37d130f468e.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>У Kaavi есть строка $$$T$$$ длины $$$m$$$ и все строки, имеющие префикс $$$T$$$ это магические заклинания. У Kaavi также есть строка $$$S$$$ длины $$$n$$$ и пустая строка $$$A$$$.</p><p>Во время гадания, Kaavi нужно применить некоторую последовательность операций. Есть две различные операции:</p><ul><li> Удалить первый символ строки $$$S$$$ и добавить его <span class="tex-font-style-bf">в начало</span> строки $$$A$$$.</li><li> Удалить первый символ строки $$$S$$$ и добавить его <span class="tex-font-style-bf">в конец</span> строки $$$A$$$.</li></ul><p>Kaavi может сделать <span class="tex-font-style-bf">не более, чем</span> $$$n$$$ операций. Для того, чтобы завершить гадание, она хочет узнать количество различных последовательностей операций, для того, чтобы сделать $$$A$$$ магическим заклинанием (то есть эта строка имеет префикс $$$T$$$). Как ее ассистент, можете ли вы помочь ей? Поскольку ответ может быть очень большим, Kaavi хочет знать его остаток при делении на $$$998\,244\,353$$$.</p><p>Две последовательности операций считаются различными, если они различаются по длине или существует такое $$$i$$$, что их $$$i$$$-е операции различаются.</p><p>Подстрокой называется некоторая последовательность последовательных символов строки. Префиксом строки $$$S$$$ называется подстрока $$$S$$$, которая начинается в начале строки $$$S$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится строка $$$S$$$ длины $$$n$$$ ($$$1 \leq n \leq 3000$$$).</p><p>Во второй строке находится строка $$$T$$$ длины $$$m$$$ ($$$1 \leq m \leq n$$$).</p><p>Обе строки состоят только из строчных латинских символов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число  — ответ на задачу по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> abab ba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12</pre></div><div class="input"><div class="title">Входные данные</div><pre> defineintlonglong signedmain </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0</pre></div><div class="input"><div class="title">Входные данные</div><pre> rotator rotator </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4</pre></div><div class="input"><div class="title">Входные данные</div><pre> cacdcdbbbb bdcaccdbbb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/59b1aeccd6c5b78703012f04c99eb547b718f003.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Красные строки это магические заклинания. В первой операции, Kaavi может добавить символ «<span class="tex-font-style-tt">a</span>» в начало или в конец $$$A$$$. Хотя в обоих случаях результат будет одинаковым, это две разные операции. Поэтому ответ $$$6\times2=12$$$.</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 11:00: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:'81249ce17e0f1622',t:'MTY5NjY2NTY1MS42NTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0440\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", "\u0441\u0442\u0440\u043e\u043a\u0438", "*2200"]
1336D
1336
D
ru
D. Yui и маджонг
<div class="problem-statement"><div class="header"><div class="title">D. Yui и маджонг</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Yui девочка, которая очень любит играть в маджонг.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/52d3020384f00426f2e00e8e88039c5fc29bbdd8.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>У нее есть таинственный набор, который состоит из нескольких плиток (этот набор может быть пустым). Каждая плитка содержит целое число от $$$1$$$ до $$$n$$$ и <span class="tex-font-style-bf">не больше, чем $$$n$$$ плиток</span> в множестве имеют одинаковое значение. Таким образом, в множество содержит не больше, чем $$$n^2$$$ плиток.</p><p>Вы хотите узнать, какие числа написаны на плитках в множестве. Для этого Yui хочет сыграть с вами в игру.</p><p>Давайте назовем множество, состоящее из <span class="tex-font-style-bf">трех</span> плиток <span class="tex-font-style-it">равной тройкой</span>, если значения на плитках одинаковые. Например, $$$\{2,\,2,\,2\}$$$ это равная тройка, а $$$\{2,\,3,\,3\}$$$ нет.</p><p>Давайте назовем множество, состоящее из <span class="tex-font-style-bf">трех</span> плиток <span class="tex-font-style-it">последовательной тройкой</span>, если значения на плитках последовательные целые числа. Например, $$$\{2,\,3,\,4\}$$$ это последовательная тройка, а $$$\{1,\,3,\,5\}$$$ нет.</p><p>Сначала, Yui называет вам количество подмножеств плиток, которые являются равными тройками и количество подмножеств плиток, которые являются последовательными тройками в ее множестве плиток. После этого, вы можете добавить плитку с целым числом от $$$1$$$ до $$$n$$$ в множество <span class="tex-font-style-bf">не более, чем $$$n$$$ раз</span>. Каждый раз добавляя плитку, в ответ вы получите количество подмножеств плиток в текущем множестве плиток, которые являются равными тройками и количество подмножеств плиток в текущем множестве плиток, которые являются последовательными тройками.</p><p>Обратите внимание, что любые две различные плитки с одинаковым значением считаются различными. Другими словами, в множестве $$$\{1,\,1,\,2,\,2,\,3\}$$$ вы можете найти $$$4$$$ подмножества $$$\{1,\,2,\,3\}$$$.</p><p>Угадайте количество плиток в изначальном множестве с числом $$$i$$$ для всех целых чисел $$$i$$$ от $$$1$$$ до $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$4 \le n \le 100$$$).</p><p>Во второй строке находится два целых числа, равные количеству подмножеств плиток, которые являются равными тройками и количеству подмножеств плиток, которые являются последовательными тройками в изначальном множестве плиток.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Когда ваша программа будет готова ответить, выведите строку в формате «<span class="tex-font-style-tt">! $$$a_1$$$ $$$a_2$$$ $$$\ldots$$$ $$$a_n$$$</span>» ($$$0 \le a_i \le n$$$), где $$$a_i$$$ будет равно количеству плиток в изначальном множестве с числом $$$i$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для того, чтобы добавить плитку в множество, выведите строку в формате «<span class="tex-font-style-tt">+ $$$x$$$</span>» ($$$1 \le x \le n$$$), где $$$x$$$ равно числу, которое будет на плитке, которую вы добавляете. В ответ вы должны считать два целых числа, равных количеству подмножеств плиток, которые являются равными тройками и количеству подмножеств плиток, которые являются последовательными тройками в текущем множестве плиток.</p><p>После вывода строки с запросом добавления плитки или строки с ответом не забывайте сбрасывать буфер вывода. Иначе ваше решение получит вердикт <span class="tex-font-style-tt">Idleness limit exceeded</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> в Pascall; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> обратитесь к документации для остальных языков. </li></ul><p>Вы получите вердикт <span class="tex-font-style-tt">Wrong answer</span>, если вы добавите больше, чем $$$n$$$ плиток в множество.</p><p><span class="tex-font-style-bf">Взломы</span></p><p>Для того, чтобы сделать взлом, вы должны предоставить тест в следующем формате:</p><p>В первой строке находится единственное целое число $$$n$$$ ($$$4 \le n \le 100$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$0 \le a_i \le n$$$)  — $$$a_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 1 6 2 9 5 12 5 24 6 24 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> + 1 + 1 + 2 + 5 ! 2 1 3 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, изначальное множество плиток $$$\{1, 1, 2, 3, 3, 3, 5, 5\}$$$. Оно содержит одну равную тройку $$$\{3, 3, 3\}$$$ и шесть последовательных троек, которые все равны $$$\{1, 2, 3\}$$$. После добавления в множество плитки со значением $$$1$$$ множество плиток станет $$$\{1, 1, 1, 2, 3, 3, 3, 5, 5\}$$$ и будет содержать две равные тройки $$$\{1, 1, 1\}$$$, $$$\{3, 3, 3\}$$$ и девять последовательных троек, которые все равны $$$\{1, 2, 3\}$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="c1958335aa3f06f0f31e9d8f88088651"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="a3e2a90714a5b9585ccdbcb93d817b980a2e6bb7"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c1958335aa3f06f0f31e9d8f88088651'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1336%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='c1958335aa3f06f0f31e9d8f88088651'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1336">Codeforces Round 635 (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='c1958335aa3f06f0f31e9d8f88088651'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1336/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='c1958335aa3f06f0f31e9d8f88088651'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594569"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c1958335aa3f06f0f31e9d8f88088651'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594569"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Codeforces Round #635" target="_blank">Codeforces Round #635 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10768" resourceName="Codeforces Round #635" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10772" resourceName="Codeforces Round #635 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1336">Задачи</a></li> <li><a href="/contest/1336/submit">Отослать</a></li> <li><a href="/contest/1336/my">Мои посылки</a></li> <li><a href="/contest/1336/status">Статус</a></li> <li><a href="/contest/1336/hacks">Взломы</a></li> <li><a href="/contest/1336/room/1">Комната</a></li> <li><a href="/contest/1336/standings">Положение</a></li> <li><a href="/contest/1336/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e461b5ae334ca7b89a1d7b4f26676bd99996f1e4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Yui и маджонг</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Yui девочка, которая очень любит играть в маджонг.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/52d3020384f00426f2e00e8e88039c5fc29bbdd8.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>У нее есть таинственный набор, который состоит из нескольких плиток (этот набор может быть пустым). Каждая плитка содержит целое число от $$$1$$$ до $$$n$$$ и <span class="tex-font-style-bf">не больше, чем $$$n$$$ плиток</span> в множестве имеют одинаковое значение. Таким образом, в множество содержит не больше, чем $$$n^2$$$ плиток.</p><p>Вы хотите узнать, какие числа написаны на плитках в множестве. Для этого Yui хочет сыграть с вами в игру.</p><p>Давайте назовем множество, состоящее из <span class="tex-font-style-bf">трех</span> плиток <span class="tex-font-style-it">равной тройкой</span>, если значения на плитках одинаковые. Например, $$$\{2,\,2,\,2\}$$$ это равная тройка, а $$$\{2,\,3,\,3\}$$$ нет.</p><p>Давайте назовем множество, состоящее из <span class="tex-font-style-bf">трех</span> плиток <span class="tex-font-style-it">последовательной тройкой</span>, если значения на плитках последовательные целые числа. Например, $$$\{2,\,3,\,4\}$$$ это последовательная тройка, а $$$\{1,\,3,\,5\}$$$ нет.</p><p>Сначала, Yui называет вам количество подмножеств плиток, которые являются равными тройками и количество подмножеств плиток, которые являются последовательными тройками в ее множестве плиток. После этого, вы можете добавить плитку с целым числом от $$$1$$$ до $$$n$$$ в множество <span class="tex-font-style-bf">не более, чем $$$n$$$ раз</span>. Каждый раз добавляя плитку, в ответ вы получите количество подмножеств плиток в текущем множестве плиток, которые являются равными тройками и количество подмножеств плиток в текущем множестве плиток, которые являются последовательными тройками.</p><p>Обратите внимание, что любые две различные плитки с одинаковым значением считаются различными. Другими словами, в множестве $$$\{1,\,1,\,2,\,2,\,3\}$$$ вы можете найти $$$4$$$ подмножества $$$\{1,\,2,\,3\}$$$.</p><p>Угадайте количество плиток в изначальном множестве с числом $$$i$$$ для всех целых чисел $$$i$$$ от $$$1$$$ до $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$4 \le n \le 100$$$).</p><p>Во второй строке находится два целых числа, равные количеству подмножеств плиток, которые являются равными тройками и количеству подмножеств плиток, которые являются последовательными тройками в изначальном множестве плиток.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Когда ваша программа будет готова ответить, выведите строку в формате «<span class="tex-font-style-tt">! $$$a_1$$$ $$$a_2$$$ $$$\ldots$$$ $$$a_n$$$</span>» ($$$0 \le a_i \le n$$$), где $$$a_i$$$ будет равно количеству плиток в изначальном множестве с числом $$$i$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для того, чтобы добавить плитку в множество, выведите строку в формате «<span class="tex-font-style-tt">+ $$$x$$$</span>» ($$$1 \le x \le n$$$), где $$$x$$$ равно числу, которое будет на плитке, которую вы добавляете. В ответ вы должны считать два целых числа, равных количеству подмножеств плиток, которые являются равными тройками и количеству подмножеств плиток, которые являются последовательными тройками в текущем множестве плиток.</p><p>После вывода строки с запросом добавления плитки или строки с ответом не забывайте сбрасывать буфер вывода. Иначе ваше решение получит вердикт <span class="tex-font-style-tt">Idleness limit exceeded</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> в Pascall; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> обратитесь к документации для остальных языков. </li></ul><p>Вы получите вердикт <span class="tex-font-style-tt">Wrong answer</span>, если вы добавите больше, чем $$$n$$$ плиток в множество.</p><p><span class="tex-font-style-bf">Взломы</span></p><p>Для того, чтобы сделать взлом, вы должны предоставить тест в следующем формате:</p><p>В первой строке находится единственное целое число $$$n$$$ ($$$4 \le n \le 100$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$0 \le a_i \le n$$$)  — $$$a_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 1 6 2 9 5 12 5 24 6 24 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> + 1 + 1 + 2 + 5 ! 2 1 3 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, изначальное множество плиток $$$\{1, 1, 2, 3, 3, 3, 5, 5\}$$$. Оно содержит одну равную тройку $$$\{3, 3, 3\}$$$ и шесть последовательных троек, которые все равны $$$\{1, 2, 3\}$$$. После добавления в множество плитки со значением $$$1$$$ множество плиток станет $$$\{1, 1, 1, 2, 3, 3, 3, 5, 5\}$$$ и будет содержать две равные тройки $$$\{1, 1, 1\}$$$, $$$\{3, 3, 3\}$$$ и девять последовательных троек, которые все равны $$$\{1, 2, 3\}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:00:53</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249cea8a3a9d6f',t:'MTY5NjY2NTY1My4wOTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*3200"]
1336E2
1336
E2
ru
E2. Chiori и выбор кукол (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">E2. Chiori и выбор кукол (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это сложная версия этой задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$m$$$. Вы можете делать взломы, только если обе версии задачи сданы.</span></p><p>Chiori очень любит куклы и сейчас она собирается украсить свою спальню!</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/50f0d03acd9430cc251ade68d89b0a1d19e317b1.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>Так как Chiori коллекционирует куклы, всего у нее $$$n$$$ кукол, $$$i$$$-я из этих кукол имеет неотрицательное целое число $$$a_i$$$ ($$$a_i &lt; 2^m$$$, $$$m$$$ дано). Chiori хочет выбрать некоторых кукол (возможно ноль) для украшения. Таким образом, всего существует $$$2^n$$$ способов.</p><p>Обозначим за $$$x$$$ побитовую xor сумму значений у кукол, выбранных Chiori (в случае, если Chiori не выбрала ни одной куклы, $$$x = 0$$$). Значением способа выбора кукол назовем количество битов равных $$$1$$$ в двоичном представлении $$$x$$$. Более формально, это число также равно количеству индексов $$$0 \leq i &lt; m$$$, таких что $$$\left\lfloor \frac{x}{2^i} \right\rfloor$$$ нечетно.</p><p>Посчитайте для Chiori количество способов выбрать куклы со значением $$$i$$$ для всех целых $$$i$$$ от $$$0$$$ до $$$m$$$. Поскольку эти числа могут быть очень большими, вы должны посчитать их по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 53$$$)  — количество кукол и максимальное возможное значение выбора нескольких кукол.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i &lt; 2^m$$$)  — числа у кукол.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m+1$$$ целое число $$$p_0, p_1, \ldots, p_m$$$  — $$$p_i$$$ равно количеству способов выбрать несколько кукол, так чтобы полученное значение выбора кукол оказалось равным $$$i$$$ по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 3 5 8 14 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 6 6 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 7 11 45 14 9 19 81 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 11 20 15 10 5 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a59ad0fabef30a06b8d6acc5a12116df"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="a3e2a90714a5b9585ccdbcb93d817b980a2e6bb7"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a59ad0fabef30a06b8d6acc5a12116df'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1336%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='a59ad0fabef30a06b8d6acc5a12116df'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1336">Codeforces Round 635 (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='a59ad0fabef30a06b8d6acc5a12116df'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1336/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='a59ad0fabef30a06b8d6acc5a12116df'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594571"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a59ad0fabef30a06b8d6acc5a12116df'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594571"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Codeforces Round #635" target="_blank">Codeforces Round #635 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10768" resourceName="Codeforces Round #635" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10772" resourceName="Codeforces Round #635 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1336">Задачи</a></li> <li><a href="/contest/1336/submit">Отослать</a></li> <li><a href="/contest/1336/my">Мои посылки</a></li> <li><a href="/contest/1336/status">Статус</a></li> <li><a href="/contest/1336/hacks">Взломы</a></li> <li><a href="/contest/1336/room/1">Комната</a></li> <li><a href="/contest/1336/standings">Положение</a></li> <li><a href="/contest/1336/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5f8b22c0caba173fba45bd8575c7f31d904b312b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Chiori и выбор кукол (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это сложная версия этой задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$m$$$. Вы можете делать взломы, только если обе версии задачи сданы.</span></p><p>Chiori очень любит куклы и сейчас она собирается украсить свою спальню!</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/50f0d03acd9430cc251ade68d89b0a1d19e317b1.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>Так как Chiori коллекционирует куклы, всего у нее $$$n$$$ кукол, $$$i$$$-я из этих кукол имеет неотрицательное целое число $$$a_i$$$ ($$$a_i &lt; 2^m$$$, $$$m$$$ дано). Chiori хочет выбрать некоторых кукол (возможно ноль) для украшения. Таким образом, всего существует $$$2^n$$$ способов.</p><p>Обозначим за $$$x$$$ побитовую xor сумму значений у кукол, выбранных Chiori (в случае, если Chiori не выбрала ни одной куклы, $$$x = 0$$$). Значением способа выбора кукол назовем количество битов равных $$$1$$$ в двоичном представлении $$$x$$$. Более формально, это число также равно количеству индексов $$$0 \leq i &lt; m$$$, таких что $$$\left\lfloor \frac{x}{2^i} \right\rfloor$$$ нечетно.</p><p>Посчитайте для Chiori количество способов выбрать куклы со значением $$$i$$$ для всех целых $$$i$$$ от $$$0$$$ до $$$m$$$. Поскольку эти числа могут быть очень большими, вы должны посчитать их по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 53$$$)  — количество кукол и максимальное возможное значение выбора нескольких кукол.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i &lt; 2^m$$$)  — числа у кукол.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m+1$$$ целое число $$$p_0, p_1, \ldots, p_m$$$  — $$$p_i$$$ равно количеству способов выбрать несколько кукол, так чтобы полученное значение выбора кукол оказалось равным $$$i$$$ по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 3 5 8 14 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 6 6 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 7 11 45 14 9 19 81 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 11 20 15 10 5 0 </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/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:20</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249d32d9b33374',t:'MTY5NjY2NTY4MS4xMDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*3500"]
1336F
1336
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>Где-то в дебрях, далеко-далеко находится святая земля, которая имеет форму дерева  — связного неориентированного графа, состоящего из $$$n$$$ вершин и $$$n-1$$$ ребра. Вершины пронумерованы целыми числами от $$$1$$$ до $$$n$$$.</p><p>Всего есть $$$m$$$ путешественников, привлеченных красотой и процветанием этой земли. Каждый из них отправился в путешествие по ней. $$$i$$$-й путешественник проехал вдоль кратчайшего пути из $$$s_i$$$ в $$$t_i$$$. Во время этого путешествия, он прошел через все ребра, лежащие на кратчайшем пути из $$$s_i$$$ в $$$t_i$$$, который, как известно, единственный в дереве.</p><p>Во время своих путешествий, некоторые путешественники познакомились с остальными. Некоторые из путешественников станут друзьями. Более точно, $$$i$$$-й и $$$j$$$-й путешественники станут друзьями, тогда и только тогда, когда было <span class="tex-font-style-bf">хотя бы</span> $$$k$$$ ребер, по которым прошли и $$$i$$$-й и $$$j$$$-й путешественники.</p><p>Ваша задача состоит в том, чтобы найти количество пар путешественников $$$(i, j)$$$, удовлетворяющих следующим условиям:</p><ul> <li> $$$1 \leq i &lt; j \leq m$$$. </li><li> $$$i$$$-й и $$$j$$$-й путешественники станут друзьями. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$2 \le n, m \le 1.5 \cdot 10^5$$$, $$$1\le k\le n$$$).</p><p>Каждая из следующих $$$n-1$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), обозначающих, что существует ребро между $$$u$$$ и $$$v$$$.</p><p>$$$i$$$-я из следующих $$$m$$$ строк содержит два целых числа $$$s_i$$$ и $$$t_i$$$ ($$$1\le s_i,t_i\le n$$$, $$$s_i \neq t_i$$$), обозначающие начальную и конечную вершины $$$i$$$-го путешественника.</p><p>Гарантируется, что данные ребра образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число  — количество пар путешественников, удовлетворяющих описанным условиям.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 4 1 1 7 1 2 2 5 4 6 6 3 6 2 6 8 7 8 3 8 2 6 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4</pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 4 2 3 10 9 3 4 9 4 6 8 2 1 7 2 1 4 5 6 7 7 1 8 7 9 2 10 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 8 3 7 6 9 11 5 6 11 3 9 7 2 12 4 3 1 2 5 8 6 13 5 10 3 1 10 4 10 11 8 11 4 9 2 5 3 5 7 3 8 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><img class="tex-graphics" src="https://espresso.codeforces.com/238216da68c34b418571920cacddd6194f408878.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>В первом тесте существует $$$4$$$ пары, удовлетворяющие описанным условиям: $$$(1,2)$$$, $$$(1,3)$$$, $$$(1,4)$$$, $$$(3,4)$$$.</p><ul><li> $$$1$$$-й путешественник и $$$2$$$-й путешественник оба пройдут по ребру $$$6-8$$$. </li><li> $$$1$$$-й путешественник и $$$3$$$-й путешественник оба пройдут по ребру $$$2-6$$$. </li><li> $$$1$$$-й путешественник и $$$4$$$-й путешественник оба пройдут по ребрам $$$1-2$$$ и $$$2-6$$$. </li><li> $$$3$$$-й путешественник и $$$4$$$-й путешественник оба пройдут по ребру $$$2-6$$$. </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="3225274978f098a34193340b736a3d78"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="f1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/62424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/62424/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="a3e2a90714a5b9585ccdbcb93d817b980a2e6bb7"/> <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/62424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/62424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/62424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/62424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/62424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/62424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/62424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/62424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/62424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/62424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/62424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/62424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/62424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/62424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/62424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/62424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/62424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/1cf311b0fb117ae41b7841694774183d/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/62424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/62424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='3225274978f098a34193340b736a3d78'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/62424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/62424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/62424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1336%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='3225274978f098a34193340b736a3d78'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1336">Codeforces Round 635 (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='3225274978f098a34193340b736a3d78'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1336/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй"> разделяй и властвуй </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='3225274978f098a34193340b736a3d78'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594572"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3225274978f098a34193340b736a3d78'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594572"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Codeforces Round #635" target="_blank">Codeforces Round #635 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10768" resourceName="Codeforces Round #635" resourceManual="true" src="//codeforces.org/s/62424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10772" resourceName="Codeforces Round #635 Editorial" resourceManual="true" src="//codeforces.org/s/62424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1336">Задачи</a></li> <li><a href="/contest/1336/submit">Отослать</a></li> <li><a href="/contest/1336/my">Мои посылки</a></li> <li><a href="/contest/1336/status">Статус</a></li> <li><a href="/contest/1336/hacks">Взломы</a></li> <li><a href="/contest/1336/room/1">Комната</a></li> <li><a href="/contest/1336/standings">Положение</a></li> <li><a href="/contest/1336/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_29e069c70f712a2285fa2760eb7c6949db8f4057"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Где-то в дебрях, далеко-далеко находится святая земля, которая имеет форму дерева  — связного неориентированного графа, состоящего из $$$n$$$ вершин и $$$n-1$$$ ребра. Вершины пронумерованы целыми числами от $$$1$$$ до $$$n$$$.</p><p>Всего есть $$$m$$$ путешественников, привлеченных красотой и процветанием этой земли. Каждый из них отправился в путешествие по ней. $$$i$$$-й путешественник проехал вдоль кратчайшего пути из $$$s_i$$$ в $$$t_i$$$. Во время этого путешествия, он прошел через все ребра, лежащие на кратчайшем пути из $$$s_i$$$ в $$$t_i$$$, который, как известно, единственный в дереве.</p><p>Во время своих путешествий, некоторые путешественники познакомились с остальными. Некоторые из путешественников станут друзьями. Более точно, $$$i$$$-й и $$$j$$$-й путешественники станут друзьями, тогда и только тогда, когда было <span class="tex-font-style-bf">хотя бы</span> $$$k$$$ ребер, по которым прошли и $$$i$$$-й и $$$j$$$-й путешественники.</p><p>Ваша задача состоит в том, чтобы найти количество пар путешественников $$$(i, j)$$$, удовлетворяющих следующим условиям:</p><ul> <li> $$$1 \leq i &lt; j \leq m$$$. </li><li> $$$i$$$-й и $$$j$$$-й путешественники станут друзьями. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$2 \le n, m \le 1.5 \cdot 10^5$$$, $$$1\le k\le n$$$).</p><p>Каждая из следующих $$$n-1$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), обозначающих, что существует ребро между $$$u$$$ и $$$v$$$.</p><p>$$$i$$$-я из следующих $$$m$$$ строк содержит два целых числа $$$s_i$$$ и $$$t_i$$$ ($$$1\le s_i,t_i\le n$$$, $$$s_i \neq t_i$$$), обозначающие начальную и конечную вершины $$$i$$$-го путешественника.</p><p>Гарантируется, что данные ребра образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число  — количество пар путешественников, удовлетворяющих описанным условиям.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 4 1 1 7 1 2 2 5 4 6 6 3 6 2 6 8 7 8 3 8 2 6 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4</pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 4 2 3 10 9 3 4 9 4 6 8 2 1 7 2 1 4 5 6 7 7 1 8 7 9 2 10 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 8 3 7 6 9 11 5 6 11 3 9 7 2 12 4 3 1 2 5 8 6 13 5 10 3 1 10 4 10 11 8 11 4 9 2 5 3 5 7 3 8 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><img class="tex-graphics" src="https://espresso.codeforces.com/238216da68c34b418571920cacddd6194f408878.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>В первом тесте существует $$$4$$$ пары, удовлетворяющие описанным условиям: $$$(1,2)$$$, $$$(1,3)$$$, $$$(1,4)$$$, $$$(3,4)$$$.</p><ul><li> $$$1$$$-й путешественник и $$$2$$$-й путешественник оба пройдут по ребру $$$6-8$$$. </li><li> $$$1$$$-й путешественник и $$$3$$$-й путешественник оба пройдут по ребру $$$2-6$$$. </li><li> $$$1$$$-й путешественник и $$$4$$$-й путешественник оба пройдут по ребрам $$$1-2$$$ и $$$2-6$$$. </li><li> $$$3$$$-й путешественник и $$$4$$$-й путешественник оба пройдут по ребру $$$2-6$$$. </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/62424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:23</span> (f1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/62424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/62424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/62424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/62424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-62424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249da29b950069',t:'MTY5NjY2NTY4My4yNTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3500"]
1337A
1337
A
ru
A. Ichihime и треугольник
<div class="problem-statement"><div class="header"><div class="title">A. Ichihime и треугольник</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ichihime нынешняя жрица храма души Маджонга. Она утверждает, что она человек, несмотря на свои кошачьи ушки.</p><p>Сейчас в храме проводится соревнование по математике. Обычно Ichihime не проявляет интереса к подобным вещам, но в этот раз призом является ее любимое печенье, поэтому она решила принять участие. Сейчас она решает следующую задачу.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/460965cc95e110488641a549ff72e6b554689699.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>Вам даны четыре положительных целых числа $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, такие что $$$a \leq b \leq c \leq d$$$. </p><p>Вам нужно найти три целых числа $$$x$$$, $$$y$$$, $$$z$$$, удовлетворяющие следующим условиям:</p><ul><li> $$$a \leq x \leq b$$$.</li><li> $$$b \leq y \leq c$$$.</li><li> $$$c \leq z \leq d$$$.</li><li> Существует треугольник положительной площади, длины сторон которого равны $$$x$$$, $$$y$$$ и $$$z$$$.</li></ul><p>Ichihime хочет получить печенье, но эта задачка очень трудная для нее. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — количество тестовых случаев.</p><p>Следующие $$$t$$$ строк содержат описания тестовых случаев. Каждая строка описания тестового случая содержит четыре положительных целых числа $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$1 \leq a \leq b \leq c \leq d \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите три целых числа $$$x$$$, $$$y$$$, $$$z$$$ — три числа, которые вы нашли, удовлетворяющие описанным требованиям.</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 3 5 7 1 5 5 7 100000 200000 300000 400000 1 1 977539810 977539810 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 5 5 5 5 182690 214748 300999 1 977539810 977539810 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Одно из возможных решений для первого тестового случая:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/18f634d31f7ba8b732b09cf7534c10b3f2e3afc4.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Одно из возможных решений для второго тестового случая:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/264e51bb6d26b7a1119d7e9e96133e5ffda65898.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="0d9d0a08ae98ed159f81b68a52f023c7"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="f1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/62424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/62424/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="8b0993b1dd090de436ff9945024d8f63b07cf0b5"/> <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/62424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/62424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/62424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/62424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/62424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/62424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/62424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/62424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/62424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/62424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/62424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/62424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/62424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/62424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/62424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/62424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/62424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/1cf311b0fb117ae41b7841694774183d/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/62424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/62424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/62424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/62424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/62424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='0d9d0a08ae98ed159f81b68a52f023c7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/62424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/62424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/62424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1337%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='0d9d0a08ae98ed159f81b68a52f023c7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1337">Codeforces Round 635 (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='0d9d0a08ae98ed159f81b68a52f023c7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1337/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='0d9d0a08ae98ed159f81b68a52f023c7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594573"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0d9d0a08ae98ed159f81b68a52f023c7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594573"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Announcement" target="_blank">Announcement <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10774" resourceName="Announcement" resourceManual="true" src="//codeforces.org/s/62424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10773" resourceName="Codeforces Round #635 Editorial" resourceManual="true" src="//codeforces.org/s/62424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1337">Задачи</a></li> <li><a href="/contest/1337/submit">Отослать</a></li> <li><a href="/contest/1337/my">Мои посылки</a></li> <li><a href="/contest/1337/status">Статус</a></li> <li><a href="/contest/1337/hacks">Взломы</a></li> <li><a href="/contest/1337/room/1">Комната</a></li> <li><a href="/contest/1337/standings">Положение</a></li> <li><a href="/contest/1337/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1cc5d7c86bb8c9735222d5884def0f0f25ad529d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Ichihime и треугольник</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ichihime нынешняя жрица храма души Маджонга. Она утверждает, что она человек, несмотря на свои кошачьи ушки.</p><p>Сейчас в храме проводится соревнование по математике. Обычно Ichihime не проявляет интереса к подобным вещам, но в этот раз призом является ее любимое печенье, поэтому она решила принять участие. Сейчас она решает следующую задачу.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/460965cc95e110488641a549ff72e6b554689699.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>Вам даны четыре положительных целых числа $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, такие что $$$a \leq b \leq c \leq d$$$. </p><p>Вам нужно найти три целых числа $$$x$$$, $$$y$$$, $$$z$$$, удовлетворяющие следующим условиям:</p><ul><li> $$$a \leq x \leq b$$$.</li><li> $$$b \leq y \leq c$$$.</li><li> $$$c \leq z \leq d$$$.</li><li> Существует треугольник положительной площади, длины сторон которого равны $$$x$$$, $$$y$$$ и $$$z$$$.</li></ul><p>Ichihime хочет получить печенье, но эта задачка очень трудная для нее. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — количество тестовых случаев.</p><p>Следующие $$$t$$$ строк содержат описания тестовых случаев. Каждая строка описания тестового случая содержит четыре положительных целых числа $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$1 \leq a \leq b \leq c \leq d \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите три целых числа $$$x$$$, $$$y$$$, $$$z$$$ — три числа, которые вы нашли, удовлетворяющие описанным требованиям.</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 3 5 7 1 5 5 7 100000 200000 300000 400000 1 1 977539810 977539810 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 5 5 5 5 182690 214748 300999 1 977539810 977539810 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Одно из возможных решений для первого тестового случая:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/18f634d31f7ba8b732b09cf7534c10b3f2e3afc4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Одно из возможных решений для второго тестового случая:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/264e51bb6d26b7a1119d7e9e96133e5ffda65898.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/62424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:25</span> (f1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/62424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/62424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/62424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/62424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-62424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249daff99913c6',t:'MTY5NjY2NTY4NS4xNzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"]
1337B
1337
B
ru
B. Kana и игра Dragon Quest
<div class="problem-statement"><div class="header"><div class="title">B. Kana и игра Dragon Quest</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Кana была обыкновенной старшекласницей, пока ее не обнаружил разведчик талантов. Теперь она стала идолом. Но, в отличие от стереотипа, она обожает играть в игры.</p><p>Однажды Kana заинтересовалась новой игрой, которая называется <span class="tex-font-style-it">Dragon Quest</span>. В этой игре она должна победить дракона.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/c7715ea18024283ae27dcab024db999e77f34037.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>У дракона есть некоторое количество <span class="tex-font-style-it">очков здоровья</span>, которое изначально равно $$$x$$$. Когда количество его <span class="tex-font-style-it">очков здоровья</span> становится равным $$$0$$$ или меньше $$$0$$$, он погибает. Для того, чтобы победить дракона Kana может использовать два типа заклинаний.</p><ul><li> <span class="tex-font-style-tt">Поглощение пустотой</span> <p>Предположим, что текущее количество <span class="tex-font-style-it">очков здоровья</span> дракона равно $$$h$$$, после <span class="tex-font-style-it">применения</span> этого заклинания количество <span class="tex-font-style-it">очков здоровья</span> станет равным $$$\left\lfloor \frac{h}{2} \right\rfloor + 10$$$. Здесь за $$$\left\lfloor \frac{h}{2} \right\rfloor$$$ мы обозначаем число $$$h$$$, разделенное на два с округлением вниз.</p></li><li> <span class="tex-font-style-tt">Удар молнии</span><p>Это заклинание уменьшает количество <span class="tex-font-style-it">очков здоровья</span> на $$$10$$$. Предположим, что текущее количество <span class="tex-font-style-it">очков здоровья</span> дракона равно $$$h$$$, после <span class="tex-font-style-it">применения</span> этого заклинания, количество <span class="tex-font-style-it">очков здоровья</span> уменьшится до $$$h-10$$$.</p></li></ul><p>По некоторым причинам, Kana может <span class="tex-font-style-it">применить</span> <span class="tex-font-style-bf">не больше чем</span> $$$n$$$ <span class="tex-font-style-tt">Поглощений пустотой</span> и $$$m$$$ <span class="tex-font-style-tt">Ударов молнии</span>. Она может применять заклинания в любом порядке и <span class="tex-font-style-bf">не обязана</span> применить все эти заклинания. Kana не очень хороша в математике, поэтому она просит вас помочь ей определить, сможет ли она победить дракона.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — количество тестовых случаев.</p><p>Следующие $$$t$$$ строк содержат описания тестовых случаев. Каждая строка описания тестового случая содержит три целых числа $$$x$$$, $$$n$$$, $$$m$$$ ($$$1\le x \le 10^5$$$, $$$0\le n,m\le30$$$)  — изначальное количество <span class="tex-font-style-it">очков здоровья</span> дракона, максимальное количество <span class="tex-font-style-tt">Поглощений пустотой</span> и <span class="tex-font-style-tt">Ударов молнии</span>, которое Kana может <span class="tex-font-style-it">применить</span>, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если возможно победить дракона, выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек). Иначе, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждый символ в любом регистре (в верхнем или нижнем).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 100 3 4 189 3 4 64 2 3 63 2 3 30 27 7 10 9 1 69117 21 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO NO YES YES YES YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Одна из возможных последовательностей применения заклинаний в первом тестовом случае такая:</p><ul><li> <span class="tex-font-style-tt">Поглощение пустотой</span> $$$\left\lfloor \frac{100}{2} \right\rfloor + 10=60$$$.</li><li> <span class="tex-font-style-tt">Удар молнии</span> $$$60-10=50$$$.</li><li> <span class="tex-font-style-tt">Поглощение пустотой</span> $$$\left\lfloor \frac{50}{2} \right\rfloor + 10=35$$$.</li><li> <span class="tex-font-style-tt">Поглощение пустотой</span> $$$\left\lfloor \frac{35}{2} \right\rfloor + 10=27$$$.</li><li> <span class="tex-font-style-tt">Удар молнии</span> $$$27-10=17$$$.</li><li> <span class="tex-font-style-tt">Удар молнии</span> $$$17-10=7$$$.</li><li> <span class="tex-font-style-tt">Удар молнии</span> $$$7-10=-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="6ccd34580d0a9726f1147a6d888063d8"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="i2"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/51702/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/51702/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="8b0993b1dd090de436ff9945024d8f63b07cf0b5"/> <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/51702/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/51702/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/51702/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/51702/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/51702/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/51702/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/51702/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/51702/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/51702/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/51702/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/51702/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/51702/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/51702/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/51702/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/51702/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/51702/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/51702/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/aa81c568c8ca94ab996a291578edc1cc/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/51702/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/51702/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/51702/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/51702/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/51702/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='6ccd34580d0a9726f1147a6d888063d8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/51702/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/51702/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/51702/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1337%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='6ccd34580d0a9726f1147a6d888063d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1337">Codeforces Round 635 (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='6ccd34580d0a9726f1147a6d888063d8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1337/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='6ccd34580d0a9726f1147a6d888063d8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594574"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6ccd34580d0a9726f1147a6d888063d8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594574"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Announcement" target="_blank">Announcement <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10774" resourceName="Announcement" resourceManual="true" src="//codeforces.org/s/51702/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10773" resourceName="Codeforces Round #635 Editorial" resourceManual="true" src="//codeforces.org/s/51702/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1337">Задачи</a></li> <li><a href="/contest/1337/submit">Отослать</a></li> <li><a href="/contest/1337/my">Мои посылки</a></li> <li><a href="/contest/1337/status">Статус</a></li> <li><a href="/contest/1337/hacks">Взломы</a></li> <li><a href="/contest/1337/room/1">Комната</a></li> <li><a href="/contest/1337/standings">Положение</a></li> <li><a href="/contest/1337/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_45e2cdb8fb10409ed305edb7ebc5cc8905f959c8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Kana и игра Dragon Quest</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Кana была обыкновенной старшекласницей, пока ее не обнаружил разведчик талантов. Теперь она стала идолом. Но, в отличие от стереотипа, она обожает играть в игры.</p><p>Однажды Kana заинтересовалась новой игрой, которая называется <span class="tex-font-style-it">Dragon Quest</span>. В этой игре она должна победить дракона.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/c7715ea18024283ae27dcab024db999e77f34037.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>У дракона есть некоторое количество <span class="tex-font-style-it">очков здоровья</span>, которое изначально равно $$$x$$$. Когда количество его <span class="tex-font-style-it">очков здоровья</span> становится равным $$$0$$$ или меньше $$$0$$$, он погибает. Для того, чтобы победить дракона Kana может использовать два типа заклинаний.</p><ul><li> <span class="tex-font-style-tt">Поглощение пустотой</span> <p>Предположим, что текущее количество <span class="tex-font-style-it">очков здоровья</span> дракона равно $$$h$$$, после <span class="tex-font-style-it">применения</span> этого заклинания количество <span class="tex-font-style-it">очков здоровья</span> станет равным $$$\left\lfloor \frac{h}{2} \right\rfloor + 10$$$. Здесь за $$$\left\lfloor \frac{h}{2} \right\rfloor$$$ мы обозначаем число $$$h$$$, разделенное на два с округлением вниз.</p></li><li> <span class="tex-font-style-tt">Удар молнии</span><p>Это заклинание уменьшает количество <span class="tex-font-style-it">очков здоровья</span> на $$$10$$$. Предположим, что текущее количество <span class="tex-font-style-it">очков здоровья</span> дракона равно $$$h$$$, после <span class="tex-font-style-it">применения</span> этого заклинания, количество <span class="tex-font-style-it">очков здоровья</span> уменьшится до $$$h-10$$$.</p></li></ul><p>По некоторым причинам, Kana может <span class="tex-font-style-it">применить</span> <span class="tex-font-style-bf">не больше чем</span> $$$n$$$ <span class="tex-font-style-tt">Поглощений пустотой</span> и $$$m$$$ <span class="tex-font-style-tt">Ударов молнии</span>. Она может применять заклинания в любом порядке и <span class="tex-font-style-bf">не обязана</span> применить все эти заклинания. Kana не очень хороша в математике, поэтому она просит вас помочь ей определить, сможет ли она победить дракона.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — количество тестовых случаев.</p><p>Следующие $$$t$$$ строк содержат описания тестовых случаев. Каждая строка описания тестового случая содержит три целых числа $$$x$$$, $$$n$$$, $$$m$$$ ($$$1\le x \le 10^5$$$, $$$0\le n,m\le30$$$)  — изначальное количество <span class="tex-font-style-it">очков здоровья</span> дракона, максимальное количество <span class="tex-font-style-tt">Поглощений пустотой</span> и <span class="tex-font-style-tt">Ударов молнии</span>, которое Kana может <span class="tex-font-style-it">применить</span>, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если возможно победить дракона, выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек). Иначе, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждый символ в любом регистре (в верхнем или нижнем).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 100 3 4 189 3 4 64 2 3 63 2 3 30 27 7 10 9 1 69117 21 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO NO YES YES YES YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Одна из возможных последовательностей применения заклинаний в первом тестовом случае такая:</p><ul><li> <span class="tex-font-style-tt">Поглощение пустотой</span> $$$\left\lfloor \frac{100}{2} \right\rfloor + 10=60$$$.</li><li> <span class="tex-font-style-tt">Удар молнии</span> $$$60-10=50$$$.</li><li> <span class="tex-font-style-tt">Поглощение пустотой</span> $$$\left\lfloor \frac{50}{2} \right\rfloor + 10=35$$$.</li><li> <span class="tex-font-style-tt">Поглощение пустотой</span> $$$\left\lfloor \frac{35}{2} \right\rfloor + 10=27$$$.</li><li> <span class="tex-font-style-tt">Удар молнии</span> $$$27-10=17$$$.</li><li> <span class="tex-font-style-tt">Удар молнии</span> $$$17-10=7$$$.</li><li> <span class="tex-font-style-tt">Удар молнии</span> $$$7-10=-3$$$.</li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/51702"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:26</span> (i2).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/51702/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/51702/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/51702/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/51702/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-51702.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249dbc2aa39d52',t:'MTY5NjY2NTY4Ni41OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*900"]
1337C
1337
C
ru
C. Linova и королевство
<div class="problem-statement"><div class="header"><div class="title">C. Linova и королевство</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Написание легких романов является очень важной частью жизни Linova. Прошлой ночью ей приснилось сказочное королевство. Linova написала легкий роман про это королевство, как только проснулась. Конечно, она стала его королевой.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/df63f4ac458c231c1258e895434dcb4c2f090f09.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>Всего есть $$$n$$$ городов и $$$n-1$$$ двусторонняя дорога, соединяющая некоторые пары городов королевства. Из любого города вы можете попасть в любой другой город, пройдя по некоторым дорогам. Города пронумерованы от $$$1$$$ до $$$n$$$ и город $$$1$$$ является столицей королевства. Таким образом, структура королевства является деревом.</p><p>Как королева, Linova планирует выбрать <span class="tex-font-style-bf">ровно</span> $$$k$$$ городов для развития индустрии, тогда как в остальных городах будет развиваться туризм. Столица также может быть как индустриальным, так и туристическим городом.</p><p>Раз в год в столице будет проходить встреча. Для участия во встрече, каждый <span class="tex-font-style-bf">индустриальный город</span> посылает участника. Все посланники приедут в столицу по кратчайшему пути (который как известно единственный в дереве).</p><p>Путешествие по туристическим городам очень приятно. Для каждого посланника, его <span class="tex-font-style-it">уровень счастья</span> равен количеству <span class="tex-font-style-bf">туристических городов</span> на его пути.</p><p>Для того, чтобы люди любили королеву, Linova хочет выбрать $$$k$$$ городов так, чтобы максимизировать сумму <span class="tex-font-style-it">уровней счастья</span> всех посланников. Можете ли вы посчитать максимальную возможную сумму для нее?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k&lt; n$$$)  — количество городов и индустриальных городов, соответственно.</p><p>Каждая из следующих $$$n-1$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1\le u,v\le n$$$), обозначающих наличие дороги, соединяющей города $$$u$$$ и $$$v$$$.</p><p>Гарантируется, что из любого города можно достичь любой другой по дорогам.</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> 7 4 1 2 1 3 1 4 3 5 3 6 4 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 1 2 1 3 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 5 7 5 1 7 6 1 3 7 8 3 2 1 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><img class="tex-graphics" src="https://espresso.codeforces.com/d811810ac8e2c43cb201a3388ae50f1b3e17a687.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>В первом тесте, Linova может выбрать города $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ для развития индустрии, тогда <span class="tex-font-style-it">уровень счастья</span> посланника из города $$$2$$$ будет равен $$$1$$$, <span class="tex-font-style-it">уровни счастья</span> посланников из городов $$$5$$$, $$$6$$$, $$$7$$$ будут равны $$$2$$$. Таким образом, сумма <span class="tex-font-style-it">уровней счастья</span> будет равна $$$7$$$ и можно доказать, что это максимальная возможная сумма, которая может быть.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/3ffb39c877eca7565234f5b27836c176c6a85f3f.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Во втором тесте, выбрав города $$$3$$$ и $$$4$$$ для развития индустрии можно достичь суммы $$$3$$$, но обратите внимание, что Linova планирует выбрать <span class="tex-font-style-bf">ровно</span> $$$k$$$ городов для развития индустрии, поэтому максимальная сумма равна $$$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="01ee87ee365754e9eaf16cf887fb9813"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k2"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/68432/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/68432/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="8b0993b1dd090de436ff9945024d8f63b07cf0b5"/> <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/68432/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/68432/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/68432/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/68432/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/68432/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/68432/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/68432/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/68432/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/68432/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/68432/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/68432/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/68432/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/68432/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/68432/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/68432/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/68432/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/68432/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/66d310749d7776100c0c917a125546dd/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/68432/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/68432/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='01ee87ee365754e9eaf16cf887fb9813'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/68432/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/68432/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/68432/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1337%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='01ee87ee365754e9eaf16cf887fb9813'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1337">Codeforces Round 635 (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='01ee87ee365754e9eaf16cf887fb9813'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1337/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='01ee87ee365754e9eaf16cf887fb9813'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594575"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='01ee87ee365754e9eaf16cf887fb9813'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594575"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Announcement" target="_blank">Announcement <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10774" resourceName="Announcement" resourceManual="true" src="//codeforces.org/s/68432/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10773" resourceName="Codeforces Round #635 Editorial" resourceManual="true" src="//codeforces.org/s/68432/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1337">Задачи</a></li> <li><a href="/contest/1337/submit">Отослать</a></li> <li><a href="/contest/1337/my">Мои посылки</a></li> <li><a href="/contest/1337/status">Статус</a></li> <li><a href="/contest/1337/hacks">Взломы</a></li> <li><a href="/contest/1337/room/1">Комната</a></li> <li><a href="/contest/1337/standings">Положение</a></li> <li><a href="/contest/1337/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_02b2a8978cecd6767b7c25738c8472743f409c85"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Linova и королевство</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Написание легких романов является очень важной частью жизни Linova. Прошлой ночью ей приснилось сказочное королевство. Linova написала легкий роман про это королевство, как только проснулась. Конечно, она стала его королевой.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/df63f4ac458c231c1258e895434dcb4c2f090f09.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>Всего есть $$$n$$$ городов и $$$n-1$$$ двусторонняя дорога, соединяющая некоторые пары городов королевства. Из любого города вы можете попасть в любой другой город, пройдя по некоторым дорогам. Города пронумерованы от $$$1$$$ до $$$n$$$ и город $$$1$$$ является столицей королевства. Таким образом, структура королевства является деревом.</p><p>Как королева, Linova планирует выбрать <span class="tex-font-style-bf">ровно</span> $$$k$$$ городов для развития индустрии, тогда как в остальных городах будет развиваться туризм. Столица также может быть как индустриальным, так и туристическим городом.</p><p>Раз в год в столице будет проходить встреча. Для участия во встрече, каждый <span class="tex-font-style-bf">индустриальный город</span> посылает участника. Все посланники приедут в столицу по кратчайшему пути (который как известно единственный в дереве).</p><p>Путешествие по туристическим городам очень приятно. Для каждого посланника, его <span class="tex-font-style-it">уровень счастья</span> равен количеству <span class="tex-font-style-bf">туристических городов</span> на его пути.</p><p>Для того, чтобы люди любили королеву, Linova хочет выбрать $$$k$$$ городов так, чтобы максимизировать сумму <span class="tex-font-style-it">уровней счастья</span> всех посланников. Можете ли вы посчитать максимальную возможную сумму для нее?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k&lt; n$$$)  — количество городов и индустриальных городов, соответственно.</p><p>Каждая из следующих $$$n-1$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1\le u,v\le n$$$), обозначающих наличие дороги, соединяющей города $$$u$$$ и $$$v$$$.</p><p>Гарантируется, что из любого города можно достичь любой другой по дорогам.</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> 7 4 1 2 1 3 1 4 3 5 3 6 4 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 1 2 1 3 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 5 7 5 1 7 6 1 3 7 8 3 2 1 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><img class="tex-graphics" src="https://espresso.codeforces.com/d811810ac8e2c43cb201a3388ae50f1b3e17a687.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>В первом тесте, Linova может выбрать города $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ для развития индустрии, тогда <span class="tex-font-style-it">уровень счастья</span> посланника из города $$$2$$$ будет равен $$$1$$$, <span class="tex-font-style-it">уровни счастья</span> посланников из городов $$$5$$$, $$$6$$$, $$$7$$$ будут равны $$$2$$$. Таким образом, сумма <span class="tex-font-style-it">уровней счастья</span> будет равна $$$7$$$ и можно доказать, что это максимальная возможная сумма, которая может быть.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/3ffb39c877eca7565234f5b27836c176c6a85f3f.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Во втором тесте, выбрав города $$$3$$$ и $$$4$$$ для развития индустрии можно достичь суммы $$$3$$$, но обратите внимание, что Linova планирует выбрать <span class="tex-font-style-bf">ровно</span> $$$k$$$ городов для развития индустрии, поэтому максимальная сумма равна $$$2$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/68432"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:28</span> (k2).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/68432/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/68432/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/68432/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/68432/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-68432.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249dc50be313c6',t:'MTY5NjY2NTY4OC4xMTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1600"]
1337D
1337
D
ru
D. Xenia и разноцветные камушки
<div class="problem-statement"><div class="header"><div class="title">D. Xenia и разноцветные камушки</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>Xenia девочка, рожденная дворянкой. От скуки и одиночества, Xenia вынуждена сама искать какие-то способы развлечься.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/f3da718b55ccc1ed3494e6615f1db496fd70b0ad.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>Недавно Xenia купила $$$n_r$$$ красных камушков, $$$n_g$$$ зеленых камушков и $$$n_b$$$ голубых камушков. Каждый камушек имеет некоторый вес.</p><p>Сейчас она хочет выбрать три камушка.</p><p>Xenia любит разноцветные вещи, поэтому она выберет ровно один камушек каждого цвета.</p><p>Xenia любит баланс, поэтому она хочет выбрать камушки с как можно меньшей разнице в весе.</p><p>Более точно, если положить веса выбранных камушков за $$$x$$$, $$$y$$$ и $$$z$$$, Xenia хочет выбрать камушки, так, чтобы значение $$$(x-y)^2+(y-z)^2+(z-x)^2$$$ было как можно меньше. Как ее лучший друг, можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t \le 100$$$)  — количество тестовых случаев. Затем следует описание $$$t$$$ тестовых случаев.</p><p>Первая строка описания каждого тестового случая содержит три целых числа $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — количество красных камушков, зеленых камушков и голубых камушков, соответственно.</p><p>Вторая строка описания каждого тестового случая содержит $$$n_r$$$ целых чисел $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ равно весу $$$i$$$-о красного камушка.</p><p>Третья строка описания каждого тестового случая содержит $$$n_g$$$ целых чисел $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ равно весу $$$i$$$-о зеленого камушка.</p><p>Четвертая строка описания каждого тестового случая содержит $$$n_b$$$ целых чисел $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ равно весу $$$i$$$-о голубого камушка.</p><p>Гарантируется, что $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (сумма берется по всем тестовым случаям).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите целое число  — минимальное возможное значение, которое Xenia может получить.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14 1999999996000000002 24 24 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, Xenia купила следующие камушки:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/7e400036e7fb1bb1013d79825f1eb0157cb807e7.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Если она возьмет красный камушек с весом $$$7$$$, зеленый камушек с весом $$$6$$$ и голубой камушек с весом $$$4$$$, она получит самый сбалансированный выбор со значением $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="fadf7a43469d8554c97114a0c7858a3e"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k2"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/68432/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/68432/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="8b0993b1dd090de436ff9945024d8f63b07cf0b5"/> <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/68432/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/68432/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/68432/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/68432/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/68432/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/68432/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/68432/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/68432/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/68432/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/68432/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/68432/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/68432/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/68432/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/68432/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/68432/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/68432/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/68432/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/66d310749d7776100c0c917a125546dd/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/68432/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/68432/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='fadf7a43469d8554c97114a0c7858a3e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/68432/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/68432/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/68432/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1337%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='fadf7a43469d8554c97114a0c7858a3e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1337">Codeforces Round 635 (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='fadf7a43469d8554c97114a0c7858a3e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1337/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='fadf7a43469d8554c97114a0c7858a3e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594576"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fadf7a43469d8554c97114a0c7858a3e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594576"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Announcement" target="_blank">Announcement <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10774" resourceName="Announcement" resourceManual="true" src="//codeforces.org/s/68432/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10773" resourceName="Codeforces Round #635 Editorial" resourceManual="true" src="//codeforces.org/s/68432/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1337">Задачи</a></li> <li><a href="/contest/1337/submit">Отослать</a></li> <li><a href="/contest/1337/my">Мои посылки</a></li> <li><a href="/contest/1337/status">Статус</a></li> <li><a href="/contest/1337/hacks">Взломы</a></li> <li><a href="/contest/1337/room/1">Комната</a></li> <li><a href="/contest/1337/standings">Положение</a></li> <li><a href="/contest/1337/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0ff690f25657c61f341ac6bc18561e96cbef2b03"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Xenia и разноцветные камушки</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>Xenia девочка, рожденная дворянкой. От скуки и одиночества, Xenia вынуждена сама искать какие-то способы развлечься.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/f3da718b55ccc1ed3494e6615f1db496fd70b0ad.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>Недавно Xenia купила $$$n_r$$$ красных камушков, $$$n_g$$$ зеленых камушков и $$$n_b$$$ голубых камушков. Каждый камушек имеет некоторый вес.</p><p>Сейчас она хочет выбрать три камушка.</p><p>Xenia любит разноцветные вещи, поэтому она выберет ровно один камушек каждого цвета.</p><p>Xenia любит баланс, поэтому она хочет выбрать камушки с как можно меньшей разнице в весе.</p><p>Более точно, если положить веса выбранных камушков за $$$x$$$, $$$y$$$ и $$$z$$$, Xenia хочет выбрать камушки, так, чтобы значение $$$(x-y)^2+(y-z)^2+(z-x)^2$$$ было как можно меньше. Как ее лучший друг, можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t \le 100$$$)  — количество тестовых случаев. Затем следует описание $$$t$$$ тестовых случаев.</p><p>Первая строка описания каждого тестового случая содержит три целых числа $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — количество красных камушков, зеленых камушков и голубых камушков, соответственно.</p><p>Вторая строка описания каждого тестового случая содержит $$$n_r$$$ целых чисел $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ равно весу $$$i$$$-о красного камушка.</p><p>Третья строка описания каждого тестового случая содержит $$$n_g$$$ целых чисел $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ равно весу $$$i$$$-о зеленого камушка.</p><p>Четвертая строка описания каждого тестового случая содержит $$$n_b$$$ целых чисел $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ равно весу $$$i$$$-о голубого камушка.</p><p>Гарантируется, что $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (сумма берется по всем тестовым случаям).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите целое число  — минимальное возможное значение, которое Xenia может получить.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 3 7 8 6 3 3 1 4 1 1 1 1 1 1000000000 2 2 2 1 2 5 4 6 7 2 2 2 1 2 3 4 6 7 3 4 1 3 2 1 7 3 3 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14 1999999996000000002 24 24 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, Xenia купила следующие камушки:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/7e400036e7fb1bb1013d79825f1eb0157cb807e7.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Если она возьмет красный камушек с весом $$$7$$$, зеленый камушек с весом $$$6$$$ и голубой камушек с весом $$$4$$$, она получит самый сбалансированный выбор со значением $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.</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/68432"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:29</span> (k2).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/68432/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/68432/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/68432/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/68432/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-68432.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249dce78b4759f',t:'MTY5NjY2NTY4OS41MTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\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", "*1700"]
1337E
1337
E
ru
E. Kaavi и магическое заклинание
<div class="problem-statement"><div class="header"><div class="title">E. Kaavi и магическое заклинание</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Kaavi, таинственная гадалка, глубоко верит в то, что судьба человека неизбежна и неотвратима. Конечно, она зарабатывает себе на жизнь предсказывая будущее других людей. Занимаясь гаданием, Kaavi верит, что магические заклинания могут дать ей огромную силу видеть будущее.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/e031f1a741db6090fee9d6722704d37d130f468e.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>У Kaavi есть строка $$$T$$$ длины $$$m$$$ и все строки, имеющие префикс $$$T$$$ это магические заклинания. У Kaavi также есть строка $$$S$$$ длины $$$n$$$ и пустая строка $$$A$$$.</p><p>Во время гадания, Kaavi нужно применить некоторую последовательность операций. Есть две различные операции:</p><ul><li> Удалить первый символ строки $$$S$$$ и добавить его <span class="tex-font-style-bf">в начало</span> строки $$$A$$$.</li><li> Удалить первый символ строки $$$S$$$ и добавить его <span class="tex-font-style-bf">в конец</span> строки $$$A$$$.</li></ul><p>Kaavi может сделать <span class="tex-font-style-bf">не более, чем</span> $$$n$$$ операций. Для того, чтобы завершить гадание, она хочет узнать количество различных последовательностей операций, для того, чтобы сделать $$$A$$$ магическим заклинанием (то есть эта строка имеет префикс $$$T$$$). Как ее ассистент, можете ли вы помочь ей? Поскольку ответ может быть очень большим, Kaavi хочет знать его остаток при делении на $$$998\,244\,353$$$.</p><p>Две последовательности операций считаются различными, если они различаются по длине или существует такое $$$i$$$, что их $$$i$$$-е операции различаются.</p><p>Подстрокой называется некоторая последовательность последовательных символов строки. Префиксом строки $$$S$$$ называется подстрока $$$S$$$, которая начинается в начале строки $$$S$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится строка $$$S$$$ длины $$$n$$$ ($$$1 \leq n \leq 3000$$$).</p><p>Во второй строке находится строка $$$T$$$ длины $$$m$$$ ($$$1 \leq m \leq n$$$).</p><p>Обе строки состоят только из строчных латинских символов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число  — ответ на задачу по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> abab ba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12</pre></div><div class="input"><div class="title">Входные данные</div><pre> defineintlonglong signedmain </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0</pre></div><div class="input"><div class="title">Входные данные</div><pre> rotator rotator </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4</pre></div><div class="input"><div class="title">Входные данные</div><pre> cacdcdbbbb bdcaccdbbb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/59b1aeccd6c5b78703012f04c99eb547b718f003.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Красные строки это магические заклинания. В первой операции, Kaavi может добавить символ «<span class="tex-font-style-tt">a</span>» в начало или в конец $$$A$$$. Хотя в обоих случаях результат будет одинаковым, это две разные операции. Поэтому ответ $$$6\times2=12$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="eda329f29af69869b5413baba20f343a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k2"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/68432/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/68432/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="8b0993b1dd090de436ff9945024d8f63b07cf0b5"/> <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/68432/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/68432/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/68432/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/68432/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/68432/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/68432/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/68432/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/68432/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/68432/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/68432/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/68432/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/68432/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/68432/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/68432/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/68432/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/68432/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/68432/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/66d310749d7776100c0c917a125546dd/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/68432/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/68432/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='eda329f29af69869b5413baba20f343a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/68432/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/68432/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/68432/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1337%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='eda329f29af69869b5413baba20f343a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1337">Codeforces Round 635 (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='eda329f29af69869b5413baba20f343a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1337/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2200 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='eda329f29af69869b5413baba20f343a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594577"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='eda329f29af69869b5413baba20f343a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594577"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Announcement" target="_blank">Announcement <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10774" resourceName="Announcement" resourceManual="true" src="//codeforces.org/s/68432/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10773" resourceName="Codeforces Round #635 Editorial" resourceManual="true" src="//codeforces.org/s/68432/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1337">Задачи</a></li> <li><a href="/contest/1337/submit">Отослать</a></li> <li><a href="/contest/1337/my">Мои посылки</a></li> <li><a href="/contest/1337/status">Статус</a></li> <li><a href="/contest/1337/hacks">Взломы</a></li> <li><a href="/contest/1337/room/1">Комната</a></li> <li><a href="/contest/1337/standings">Положение</a></li> <li><a href="/contest/1337/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_90db8ead7c5a410c9b20ae4eb171a4db428fafab"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Kaavi и магическое заклинание</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Kaavi, таинственная гадалка, глубоко верит в то, что судьба человека неизбежна и неотвратима. Конечно, она зарабатывает себе на жизнь предсказывая будущее других людей. Занимаясь гаданием, Kaavi верит, что магические заклинания могут дать ей огромную силу видеть будущее.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/e031f1a741db6090fee9d6722704d37d130f468e.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>У Kaavi есть строка $$$T$$$ длины $$$m$$$ и все строки, имеющие префикс $$$T$$$ это магические заклинания. У Kaavi также есть строка $$$S$$$ длины $$$n$$$ и пустая строка $$$A$$$.</p><p>Во время гадания, Kaavi нужно применить некоторую последовательность операций. Есть две различные операции:</p><ul><li> Удалить первый символ строки $$$S$$$ и добавить его <span class="tex-font-style-bf">в начало</span> строки $$$A$$$.</li><li> Удалить первый символ строки $$$S$$$ и добавить его <span class="tex-font-style-bf">в конец</span> строки $$$A$$$.</li></ul><p>Kaavi может сделать <span class="tex-font-style-bf">не более, чем</span> $$$n$$$ операций. Для того, чтобы завершить гадание, она хочет узнать количество различных последовательностей операций, для того, чтобы сделать $$$A$$$ магическим заклинанием (то есть эта строка имеет префикс $$$T$$$). Как ее ассистент, можете ли вы помочь ей? Поскольку ответ может быть очень большим, Kaavi хочет знать его остаток при делении на $$$998\,244\,353$$$.</p><p>Две последовательности операций считаются различными, если они различаются по длине или существует такое $$$i$$$, что их $$$i$$$-е операции различаются.</p><p>Подстрокой называется некоторая последовательность последовательных символов строки. Префиксом строки $$$S$$$ называется подстрока $$$S$$$, которая начинается в начале строки $$$S$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится строка $$$S$$$ длины $$$n$$$ ($$$1 \leq n \leq 3000$$$).</p><p>Во второй строке находится строка $$$T$$$ длины $$$m$$$ ($$$1 \leq m \leq n$$$).</p><p>Обе строки состоят только из строчных латинских символов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число  — ответ на задачу по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> abab ba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12</pre></div><div class="input"><div class="title">Входные данные</div><pre> defineintlonglong signedmain </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0</pre></div><div class="input"><div class="title">Входные данные</div><pre> rotator rotator </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4</pre></div><div class="input"><div class="title">Входные данные</div><pre> cacdcdbbbb bdcaccdbbb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/59b1aeccd6c5b78703012f04c99eb547b718f003.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Красные строки это магические заклинания. В первой операции, Kaavi может добавить символ «<span class="tex-font-style-tt">a</span>» в начало или в конец $$$A$$$. Хотя в обоих случаях результат будет одинаковым, это две разные операции. Поэтому ответ $$$6\times2=12$$$.</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/68432"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:30</span> (k2).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/68432/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/68432/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/68432/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/68432/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-68432.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249dd74f90164b',t:'MTY5NjY2NTY5MC45NzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0440\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", "\u0441\u0442\u0440\u043e\u043a\u0438", "*2200"]
1337F
1337
F
ru
F. Yui и маджонг
<div class="problem-statement"><div class="header"><div class="title">F. Yui и маджонг</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Yui девочка, которая очень любит играть в маджонг.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/52d3020384f00426f2e00e8e88039c5fc29bbdd8.png" style="max-width: 100.0%;max-height: 100.0%;"/></center> <p>У нее есть таинственный набор, который состоит из нескольких плиток (этот набор может быть пустым). Каждая плитка содержит целое число от $$$1$$$ до $$$n$$$ и <span class="tex-font-style-bf">не больше, чем $$$n$$$ плиток</span> в множестве имеют одинаковое значение. Таким образом, в множество содержит не больше, чем $$$n^2$$$ плиток.</p><p>Вы хотите узнать, какие числа написаны на плитках в множестве. Для этого Yui хочет сыграть с вами в игру.</p><p>Давайте назовем множество, состоящее из <span class="tex-font-style-bf">трех</span> плиток <span class="tex-font-style-it">равной тройкой</span>, если значения на плитках одинаковые. Например, $$$\{2,\,2,\,2\}$$$ это равная тройка, а $$$\{2,\,3,\,3\}$$$ нет.</p><p>Давайте назовем множество, состоящее из <span class="tex-font-style-bf">трех</span> плиток <span class="tex-font-style-it">последовательной тройкой</span>, если значения на плитках последовательные целые числа. Например, $$$\{2,\,3,\,4\}$$$ это последовательная тройка, а $$$\{1,\,3,\,5\}$$$ нет.</p><p>Сначала, Yui называет вам количество подмножеств плиток, которые являются равными тройками и количество подмножеств плиток, которые являются последовательными тройками в ее множестве плиток. После этого, вы можете добавить плитку с целым числом от $$$1$$$ до $$$n$$$ в множество <span class="tex-font-style-bf">не более, чем $$$n$$$ раз</span>. Каждый раз добавляя плитку, в ответ вы получите количество подмножеств плиток в текущем множестве плиток, которые являются равными тройками и количество подмножеств плиток в текущем множестве плиток, которые являются последовательными тройками.</p><p>Обратите внимание, что любые две различные плитки с одинаковым значением считаются различными. Другими словами, в множестве $$$\{1,\,1,\,2,\,2,\,3\}$$$ вы можете найти $$$4$$$ подмножества $$$\{1,\,2,\,3\}$$$.</p><p>Угадайте количество плиток в изначальном множестве с числом $$$i$$$ для всех целых чисел $$$i$$$ от $$$1$$$ до $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$4 \le n \le 100$$$).</p><p>Во второй строке находится два целых числа, равные количеству подмножеств плиток, которые являются равными тройками и количеству подмножеств плиток, которые являются последовательными тройками в изначальном множестве плиток.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Когда ваша программа будет готова ответить, выведите строку в формате «<span class="tex-font-style-tt">! $$$a_1$$$ $$$a_2$$$ $$$\ldots$$$ $$$a_n$$$</span>» ($$$0 \le a_i \le n$$$), где $$$a_i$$$ будет равно количеству плиток в изначальном множестве с числом $$$i$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для того, чтобы добавить плитку в множество, выведите строку в формате «<span class="tex-font-style-tt">+ $$$x$$$</span>» ($$$1 \le x \le n$$$), где $$$x$$$ равно числу, которое будет на плитке, которую вы добавляете. В ответ вы должны считать два целых числа, равных количеству подмножеств плиток, которые являются равными тройками и количеству подмножеств плиток, которые являются последовательными тройками в текущем множестве плиток.</p><p>После вывода строки с запросом добавления плитки или строки с ответом не забывайте сбрасывать буфер вывода. Иначе ваше решение получит вердикт <span class="tex-font-style-tt">Idleness limit exceeded</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> в Pascall; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> обратитесь к документации для остальных языков. </li></ul><p>Вы получите вердикт <span class="tex-font-style-tt">Wrong answer</span>, если вы добавите больше, чем $$$n$$$ плиток в множество.</p><p><span class="tex-font-style-bf">Взломы</span></p><p>Для того, чтобы сделать взлом, вы должны предоставить тест в следующем формате:</p><p>В первой строке находится единственное целое число $$$n$$$ ($$$4 \le n \le 100$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$0 \le a_i \le n$$$)  — $$$a_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 1 6 2 9 5 12 5 24 6 24 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> + 1 + 1 + 2 + 5 ! 2 1 3 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, изначальное множество плиток $$$\{1, 1, 2, 3, 3, 3, 5, 5\}$$$. Оно содержит одну равную тройку $$$\{3, 3, 3\}$$$ и шесть последовательных троек, которые все равны $$$\{1, 2, 3\}$$$. После добавления в множество плитки со значением $$$1$$$ множество плиток станет $$$\{1, 1, 1, 2, 3, 3, 3, 5, 5\}$$$ и будет содержать две равные тройки $$$\{1, 1, 1\}$$$, $$$\{3, 3, 3\}$$$ и девять последовательных троек, которые все равны $$$\{1, 2, 3\}$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="74ce84d4c1157fbbbd68fe5e7d78717c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k2"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/68432/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/68432/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="8b0993b1dd090de436ff9945024d8f63b07cf0b5"/> <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/68432/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/68432/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/68432/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/68432/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/68432/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/68432/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/68432/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/68432/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/68432/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/68432/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/68432/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/68432/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/68432/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/68432/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/68432/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/68432/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/68432/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/66d310749d7776100c0c917a125546dd/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/68432/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/68432/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/68432/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/68432/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/68432/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='74ce84d4c1157fbbbd68fe5e7d78717c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/68432/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/68432/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/68432/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1337%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='74ce84d4c1157fbbbd68fe5e7d78717c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1337">Codeforces Round 635 (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='74ce84d4c1157fbbbd68fe5e7d78717c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1337/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='74ce84d4c1157fbbbd68fe5e7d78717c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="594579"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='74ce84d4c1157fbbbd68fe5e7d78717c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="594579"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75996" title="Announcement" target="_blank">Announcement <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10774" resourceName="Announcement" resourceManual="true" src="//codeforces.org/s/68432/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76099" title="Codeforces Round #635 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10773" resourceName="Codeforces Round #635 Editorial" resourceManual="true" src="//codeforces.org/s/68432/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1337">Задачи</a></li> <li><a href="/contest/1337/submit">Отослать</a></li> <li><a href="/contest/1337/my">Мои посылки</a></li> <li><a href="/contest/1337/status">Статус</a></li> <li><a href="/contest/1337/hacks">Взломы</a></li> <li><a href="/contest/1337/room/1">Комната</a></li> <li><a href="/contest/1337/standings">Положение</a></li> <li><a href="/contest/1337/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c76628f3c33e8dac811ef294ace434ddd0c59273"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Yui и маджонг</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Yui девочка, которая очень любит играть в маджонг.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/52d3020384f00426f2e00e8e88039c5fc29bbdd8.png" style="max-width: 100.0%;max-height: 100.0%;" /></center> <p>У нее есть таинственный набор, который состоит из нескольких плиток (этот набор может быть пустым). Каждая плитка содержит целое число от $$$1$$$ до $$$n$$$ и <span class="tex-font-style-bf">не больше, чем $$$n$$$ плиток</span> в множестве имеют одинаковое значение. Таким образом, в множество содержит не больше, чем $$$n^2$$$ плиток.</p><p>Вы хотите узнать, какие числа написаны на плитках в множестве. Для этого Yui хочет сыграть с вами в игру.</p><p>Давайте назовем множество, состоящее из <span class="tex-font-style-bf">трех</span> плиток <span class="tex-font-style-it">равной тройкой</span>, если значения на плитках одинаковые. Например, $$$\{2,\,2,\,2\}$$$ это равная тройка, а $$$\{2,\,3,\,3\}$$$ нет.</p><p>Давайте назовем множество, состоящее из <span class="tex-font-style-bf">трех</span> плиток <span class="tex-font-style-it">последовательной тройкой</span>, если значения на плитках последовательные целые числа. Например, $$$\{2,\,3,\,4\}$$$ это последовательная тройка, а $$$\{1,\,3,\,5\}$$$ нет.</p><p>Сначала, Yui называет вам количество подмножеств плиток, которые являются равными тройками и количество подмножеств плиток, которые являются последовательными тройками в ее множестве плиток. После этого, вы можете добавить плитку с целым числом от $$$1$$$ до $$$n$$$ в множество <span class="tex-font-style-bf">не более, чем $$$n$$$ раз</span>. Каждый раз добавляя плитку, в ответ вы получите количество подмножеств плиток в текущем множестве плиток, которые являются равными тройками и количество подмножеств плиток в текущем множестве плиток, которые являются последовательными тройками.</p><p>Обратите внимание, что любые две различные плитки с одинаковым значением считаются различными. Другими словами, в множестве $$$\{1,\,1,\,2,\,2,\,3\}$$$ вы можете найти $$$4$$$ подмножества $$$\{1,\,2,\,3\}$$$.</p><p>Угадайте количество плиток в изначальном множестве с числом $$$i$$$ для всех целых чисел $$$i$$$ от $$$1$$$ до $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$4 \le n \le 100$$$).</p><p>Во второй строке находится два целых числа, равные количеству подмножеств плиток, которые являются равными тройками и количеству подмножеств плиток, которые являются последовательными тройками в изначальном множестве плиток.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Когда ваша программа будет готова ответить, выведите строку в формате «<span class="tex-font-style-tt">! $$$a_1$$$ $$$a_2$$$ $$$\ldots$$$ $$$a_n$$$</span>» ($$$0 \le a_i \le n$$$), где $$$a_i$$$ будет равно количеству плиток в изначальном множестве с числом $$$i$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для того, чтобы добавить плитку в множество, выведите строку в формате «<span class="tex-font-style-tt">+ $$$x$$$</span>» ($$$1 \le x \le n$$$), где $$$x$$$ равно числу, которое будет на плитке, которую вы добавляете. В ответ вы должны считать два целых числа, равных количеству подмножеств плиток, которые являются равными тройками и количеству подмножеств плиток, которые являются последовательными тройками в текущем множестве плиток.</p><p>После вывода строки с запросом добавления плитки или строки с ответом не забывайте сбрасывать буфер вывода. Иначе ваше решение получит вердикт <span class="tex-font-style-tt">Idleness limit exceeded</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> в Pascall; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> обратитесь к документации для остальных языков. </li></ul><p>Вы получите вердикт <span class="tex-font-style-tt">Wrong answer</span>, если вы добавите больше, чем $$$n$$$ плиток в множество.</p><p><span class="tex-font-style-bf">Взломы</span></p><p>Для того, чтобы сделать взлом, вы должны предоставить тест в следующем формате:</p><p>В первой строке находится единственное целое число $$$n$$$ ($$$4 \le n \le 100$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$0 \le a_i \le n$$$)  — $$$a_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 1 6 2 9 5 12 5 24 6 24 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> + 1 + 1 + 2 + 5 ! 2 1 3 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, изначальное множество плиток $$$\{1, 1, 2, 3, 3, 3, 5, 5\}$$$. Оно содержит одну равную тройку $$$\{3, 3, 3\}$$$ и шесть последовательных троек, которые все равны $$$\{1, 2, 3\}$$$. После добавления в множество плитки со значением $$$1$$$ множество плиток станет $$$\{1, 1, 1, 2, 3, 3, 3, 5, 5\}$$$ и будет содержать две равные тройки $$$\{1, 1, 1\}$$$, $$$\{3, 3, 3\}$$$ и девять последовательных троек, которые все равны $$$\{1, 2, 3\}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/68432"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:32</span> (k2).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/68432/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/68432/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/68432/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/68432/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-68432.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249de07e830c48',t:'MTY5NjY2NTY5Mi4yOTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3200"]
1338A
1338
A
ru
A. Прибавление степеней
<div class="problem-statement"><div class="header"><div class="title">A. Прибавление степеней</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть массив $$$a$$$ длины $$$n$$$. Для каждого положительного числа $$$x$$$ в течение $$$x$$$-й секунды вы собираетесь выполнить следующую операцию:</p><ul> <li> Выберите несколько различных индексов $$$i_{1}, i_{2}, \ldots, i_{k}$$$, которые находятся в диапазоне от $$$1$$$ до $$$n$$$ включительно, и добавьте $$$2^{x-1}$$$ к каждой соответствующей позиции в $$$a$$$. Формально $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ для $$$j = 1, 2, \ldots, k$$$. <span class="tex-font-style-bf">Обратите внимание, что вы можете также не выбрать ни одного индекса.</span> </li></ul><p>Вы должны сделать $$$a$$$ неубывающим как можно быстрее. Найдите наименьшее число $$$T$$$ такое, что вы можете сделать массив неубывающим не позднее, чем через $$$T$$$ секунд.</p><p>Массив $$$a$$$ называется неубывающим, если и только если $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^{4}$$$)  — количество тестовых случаев.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^{5}$$$)  — длину массива $$$a$$$. Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превышает $$$10^{5}$$$.</p><p>Вторая строка каждого теста содержит $$$n$$$ целых чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).</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 4 1 7 6 5 5 1 2 3 4 5 2 0 -4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, если вы выберете индексы $$$3, 4$$$ на $$$1$$$-й секунде и $$$4$$$ на $$$2$$$-й секунде, то $$$a$$$ станет равным $$$[1, 7, 7, 8]$$$. Есть и другие способы сделать $$$a$$$ неубывающим за $$$2$$$ секунды, но вы не сделать его неубывающим быстрее.</p><p>Во втором тестовом случае $$$a$$$ уже неубывающий, поэтому ответ равен $$$0$$$.</p><p>В третьем тестовом случае, если вы ничего не сделаете в первые $$$2$$$ секунды и в течение $$$3$$$-й секунды выберете индекс $$$2$$$, $$$a$$$ станет равным $$$[0, 0]$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a40acf0cab6920e0fafabf655b70a37a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="5c85cbb657e064c2cfa3c38de5074b5925e3ec82"/> <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/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a40acf0cab6920e0fafabf655b70a37a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/81027/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/81027/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1338%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='a40acf0cab6920e0fafabf655b70a37a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1338">Codeforces Round 633 (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='a40acf0cab6920e0fafabf655b70a37a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1338/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='a40acf0cab6920e0fafabf655b70a37a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590531"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a40acf0cab6920e0fafabf655b70a37a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590531"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10753" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10760" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1338">Задачи</a></li> <li><a href="/contest/1338/submit">Отослать</a></li> <li><a href="/contest/1338/my">Мои посылки</a></li> <li><a href="/contest/1338/status">Статус</a></li> <li><a href="/contest/1338/hacks">Взломы</a></li> <li><a href="/contest/1338/room/1">Комната</a></li> <li><a href="/contest/1338/standings">Положение</a></li> <li><a href="/contest/1338/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_bf05a3525d30face1aa06d2010f92d5fad7f4402"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Прибавление степеней</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть массив $$$a$$$ длины $$$n$$$. Для каждого положительного числа $$$x$$$ в течение $$$x$$$-й секунды вы собираетесь выполнить следующую операцию:</p><ul> <li> Выберите несколько различных индексов $$$i_{1}, i_{2}, \ldots, i_{k}$$$, которые находятся в диапазоне от $$$1$$$ до $$$n$$$ включительно, и добавьте $$$2^{x-1}$$$ к каждой соответствующей позиции в $$$a$$$. Формально $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ для $$$j = 1, 2, \ldots, k$$$. <span class="tex-font-style-bf">Обратите внимание, что вы можете также не выбрать ни одного индекса.</span> </li></ul><p>Вы должны сделать $$$a$$$ неубывающим как можно быстрее. Найдите наименьшее число $$$T$$$ такое, что вы можете сделать массив неубывающим не позднее, чем через $$$T$$$ секунд.</p><p>Массив $$$a$$$ называется неубывающим, если и только если $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^{4}$$$)  — количество тестовых случаев.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^{5}$$$)  — длину массива $$$a$$$. Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превышает $$$10^{5}$$$.</p><p>Вторая строка каждого теста содержит $$$n$$$ целых чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).</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 4 1 7 6 5 5 1 2 3 4 5 2 0 -4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, если вы выберете индексы $$$3, 4$$$ на $$$1$$$-й секунде и $$$4$$$ на $$$2$$$-й секунде, то $$$a$$$ станет равным $$$[1, 7, 7, 8]$$$. Есть и другие способы сделать $$$a$$$ неубывающим за $$$2$$$ секунды, но вы не сделать его неубывающим быстрее.</p><p>Во втором тестовом случае $$$a$$$ уже неубывающий, поэтому ответ равен $$$0$$$.</p><p>В третьем тестовом случае, если вы ничего не сделаете в первые $$$2$$$ секунды и в течение $$$3$$$-й секунды выберете индекс $$$2$$$, $$$a$$$ станет равным $$$[0, 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/81027"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:33</span> (h1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/81027/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249de89cea1687',t:'MTY5NjY2NTY5My44NzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1500"]
https://codeforces.com/blog/entry/75913
<!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="8bc765f3680682fd8f2decef62cad97d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Codeforces Round #633 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #633 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='8bc765f3680682fd8f2decef62cad97d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F75913">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='8bc765f3680682fd8f2decef62cad97d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:36:25</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:36:25</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='8bc765f3680682fd8f2decef62cad97d'/> <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/McDic">McDic</a></li> <li class="current selectedLava"><a href="/blog/McDic">Blog</a></li> <li><a href="/teams/with/McDic">Teams</a></li> <li><a href="/submissions/McDic">Submissions</a></li> <li><a href="/groups/with/McDic">Groups</a></li> <li><a href="/contests/with/McDic">Contests</a></li> <li><a href="/contests/writer/McDic">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/McDic" style="text-decoration:none;color:black !important;">McDic's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="76444"> <div class="title"> <a href="/blog/entry/75913"> <p>Codeforces Round #633 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a>, <a href="/topic/76444/en2">history</a>, <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p>Hello! I hope all of you enjoyed my contest!</p> <div class="problemTutorial" problemcode="1339A">Tutorial is loading...</div><p><strong>Behind story of A</strong>:</p> <ul> <li>I tried to make the easiest Div2A ever. Will it work? :)</li> </ul> <div class="problemTutorial" problemcode="1339B">Tutorial is loading...</div><p><strong>Behind story of B</strong>:</p> <ul> <li>I tried to block various heuristics. There were some critical heuristics which could pass so many cases. Fortunately I blocked them during testing period, so I hope there won't be much FST this time.</li> </ul> <div class="problemTutorial" problemcode="1338A">Tutorial is loading...</div><p><strong>Behind story of D2C/D1A</strong>:</p> <ul> <li>Originally, there was a different problem for this position. But it used XOR. As I made new D2E/D1C problem, I threw old D2C/D1A away and put this.</li> </ul> <div class="problemTutorial" problemcode="1338B">Tutorial is loading...</div><p><strong>Behind story of D2D/D1B</strong>:</p> <ul> <li>This problem is the most popular problem among testers. I also like this problem a lot.</li> </ul> <div class="problemTutorial" problemcode="1338C">Tutorial is loading...</div><p><strong>Behind story of D2E/D1C</strong>:</p> <ul> <li>Feedback for this problem was too different by testers.</li> <li>I made this problem by modifying <a href="https://codeforces.com/contest/1242/problem/D">Number Discovery</a>, which is one of my previous problems.</li> <li>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this.</li> </ul> <div class="problemTutorial" problemcode="1338D">Tutorial is loading...</div><p><strong>Behind story of D1D</strong>:</p> <ul> <li>This problem was supposed to be D2E at first. But all LGM testers failed this problem during VC, so we thought that this problem's difficulty is high. Meanwhile, I found that old D1D problem can be easily googled, so we removed that problem, push this problem to be D1D, and made another D1C problem. I will share old D1D later.</li> </ul> <div class="problemTutorial" problemcode="1338E">Tutorial is loading...</div><p><strong>Behind story of D1E</strong>:</p> <ul> <li>Thanks <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a> for writing this problem. She is genius in both singing and problemsolving.</li> </ul></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/1338" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 1)</a> </span> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1339" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-88959-76444").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "88959", blogEntryId: "75913", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=mcdic" class="tag notice" style="text-decoration: none;">mcdic</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-76444"><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'>+346</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-76444"><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/McDic"><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/McDic"> McDic </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/75913#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/75913#comments"> 225 </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="82006"> <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 (171)</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="601867" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stefdasca" style="position: relative;"> <img src='https://userpic.codeforces.org/492453/avatar/429fc64e07ff3f4.jpg'/> </a> <div><a href="/profile/stefdasca" title="Candidate Master stefdasca" class="rated-user user-violet">stefdasca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601867" href="?#comment-601867" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601867" 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="601867" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="492453" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601867"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=crOSe84Q6HQ">Video tutorial for div1A/div2C</a></p><p><a href="https://www.youtube.com/watch?v=MMtnJDMM3IE">Video tutorial for div1B/div2D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-601867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601867"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601870" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kerO_o" style="position: relative;"> <img src='https://userpic.codeforces.org/406813/avatar/a505f416e75a37bd.jpg'/> </a> <div><a href="/profile/kerO_o" title="Master kerO_o" class="rated-user user-orange">kerO_o</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601870" href="?#comment-601870" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601870" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="406813" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601870"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-601870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601870"> <li> <div class="comment"> <table class="comment-table" commentId="601963" commentParentId="601870"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601963" href="?#comment-601963" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601963" class="CommentVoteFrame" data-commentRating="30" 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:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601963"> <div class="moveup"> <div class="ttypography"><p>what does this &quot;orz&quot; mean? </p></div> </div> </div> <div class="reply info"> <a class="comment-601963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601963"> <li> <div class="comment"> <table class="comment-table" commentId="602114" commentParentId="601963"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yash18" style="position: relative;"> <img src='https://userpic.codeforces.org/858176/avatar/3cdce86e6de339b8.jpg'/> </a> <div><a href="/profile/yash18" title="Pupil yash18" class="rated-user user-green">yash18</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602114" href="?#comment-602114" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602114" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602114" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="858176" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602114"> <div class="moveup"> <div class="ttypography"><p>Bow down! Bow down to the <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602114 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602114 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602114"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601879" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SkySurfer" style="position: relative;"> <img src='https://userpic.codeforces.org/684272/avatar/41e617735365cc0e.jpg'/> </a> <div><a href="/profile/SkySurfer" title="Specialist SkySurfer" class="rated-user user-cyan">SkySurfer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601879" href="?#comment-601879" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601879" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="684272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601879"> <div class="moveup"> <div class="ttypography"><p>Best Editorial Ever ....Nice Explanation Of both Problems and Solutions . </p></div> </div> </div> <div class="reply info"> <a class="comment-601879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601879"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601890" href="?#comment-601890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601890" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601890" class="CommentVoteFrame" data-commentRating="32" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+32</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601890"> <div class="moveup"> <div class="ttypography"><p>For Div1C, I found out that the nth tuple (an, bn, cn) is basically this: (found via OEIS)</p> <ol> <li><p>an -&gt; nth number with odd number of bits</p></li> <li><p>bn -&gt; nim_multiplcation(2, an) (<a href="https://oeis.org/A006015">https://oeis.org/A006015</a>)</p></li> <li><p>cn = an ^ bn.</p></li> </ol><p>But I was still not able to solve the problem because I didn't know nim multiplication nor did I find any implementation over the net.</p></div> </div> </div> <div class="reply info"> <a class="comment-601890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601890"> <li> <div class="comment"> <table class="comment-table" commentId="601914" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601914" href="?#comment-601914" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601914" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601914"> <div class="moveup"> <div class="ttypography"><p>Nim Arithmetic is definitely overkill for this problem. </p></div> </div> </div> <div class="reply info"> <a class="comment-601914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601914"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="601919" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601919" href="?#comment-601919" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601919" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601919" class="CommentVoteFrame" data-commentRating="71" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+71</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601919"> <div class="moveup"> <div class="ttypography"><p>We found that during testing and thought it wasn't much of an issue exactly because of that, probably you'd spend more time searching about nim multiplication than if you just solved the problem lol</p></div> </div> </div> <div class="reply info"> <a class="comment-601919 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601919 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601919"> <li> <div class="comment"> <table class="comment-table" commentId="601942" commentParentId="601919"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601942" href="?#comment-601942" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601919" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601942" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601942"> <div class="moveup"> <div class="ttypography"><p>Yeah, that is what happened ... I kept on searching for nim multiplcation here and there and wasted too much time. I should have come up with some other approaches ... </p></div> </div> </div> <div class="reply info"> <a class="comment-601942 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601942 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601942"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602731" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602731" href="?#comment-602731" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602731" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602731"> <div class="moveup"> <div class="ttypography"><p>A solution with nim multiplcation: <a href="/contest/1338/submission/76499145" title="Submission 76499145 by amane-ame">76499145</a></p><p>There is no doubt that it is much more complicated than the general solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602731 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602731 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602731"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601893" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Endagorion" style="position: relative;"> <img src='https://userpic.codeforces.org/1643/avatar/5c0b493cf8428ab6.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Endagorion" title="International Grandmaster Endagorion" class="rated-user user-red">Endagorion</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601893" href="?#comment-601893" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601893" class="CommentVoteFrame" data-commentRating="192" data-commentUserId="1643" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+192</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601893"> <div class="moveup"> <div class="ttypography"><p>I don't have proof, but in div1C any triple appears to be $$$(x, x \otimes 2, x \otimes 3)$$$, where $$$\otimes$$$ is nim multiplication.</p></div> </div> </div> <div class="reply info"> <a class="comment-601893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601893"> <li> <div class="comment"> <table class="comment-table" commentId="601983" commentParentId="601893"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601983" href="?#comment-601983" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601983" class="CommentVoteFrame" data-commentRating="64" 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;">+64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601983"> <div class="moveup"> <div class="ttypography"><p>:o</p></div> </div> </div> <div class="reply info"> <a class="comment-601983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601983"> <li> <div class="comment"> <table class="comment-table" commentId="602418" commentParentId="601983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jerry__Jiang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jerry__Jiang" title="Master Jerry__Jiang" class="rated-user user-orange">Jerry__Jiang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602418" href="?#comment-602418" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601983" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602418" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1198521" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602418"> <div class="moveup"> <div class="ttypography"><p>:)</p></div> </div> </div> <div class="reply info"> <a class="comment-602418 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602418 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602418"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601939" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601939" href="?#comment-601939" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601939" 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="601939" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-41" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601939"> <div class="moveup"> <div class="ttypography"><p>[DELETED]</p></div> </div> </div> <div class="reply info"> <a class="comment-601939 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601939 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601939"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prodelta" style="position: relative;"> <img src='https://userpic.codeforces.org/847522/avatar/e144f36263828062.jpg'/> </a> <div><a href="/profile/prodelta" title="Pupil prodelta" class="rated-user user-green">prodelta</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601950" href="?#comment-601950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601950" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="847522" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601950"> <div class="moveup"> <div class="ttypography"><p>System testing is finished , Editorials are out , but my submission for Problem — A still shows Pretests Passed . Link : <a href="https://codeforces.com/contest/1339/submission/76340409">Here</a></p><p>Have I committed some fatal sin for which I am being given such a brutal punishment ?</p><p>What should I do now ?</p></div> </div> </div> <div class="reply info"> <a class="comment-601950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601950"> <li> <div class="comment"> <table class="comment-table" commentId="601964" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shubhammitt" style="position: relative;"> <img src='https://userpic.codeforces.org/785906/avatar/ecb76ca8bc2663f4.jpg'/> </a> <div><a href="/profile/shubhammitt" title="Expert shubhammitt" class="rated-user user-blue">shubhammitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601964" href="?#comment-601964" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601964" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="785906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601964"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-601964 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601964 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601964"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602003" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602003" href="?#comment-602003" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602003" 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-602003"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-602003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602003"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602451" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chidoring" style="position: relative;"> <img src='https://userpic.codeforces.org/1455809/avatar/d62042cde12a7b4e.jpg'/> </a> <div><a href="/profile/chidoring" title="Pupil chidoring" class="rated-user user-green">chidoring</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602451" href="?#comment-602451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602451" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1455809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602451"> <div class="moveup"> <div class="ttypography"><p>rip</p></div> </div> </div> <div class="reply info"> <a class="comment-602451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602451"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601953" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_DynamicCube" style="position: relative;"> <img src='https://userpic.codeforces.org/1381092/avatar/ca9726e93700302b.jpg'/> </a> <div><a href="/profile/_DynamicCube" title="Pupil _DynamicCube" class="rated-user user-green">_DynamicCube</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601953" href="?#comment-601953" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601953" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1381092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601953"> <div class="moveup"> <div class="ttypography"><p>재밌는 문제들 감사합니다! (Thank you for the interesting questions!)</p></div> </div> </div> <div class="reply info"> <a class="comment-601953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601953"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601956" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AceKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AceKing" title="Candidate Master AceKing" class="rated-user user-violet">AceKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601956" href="?#comment-601956" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601956" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="910788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601956"> <div class="moveup"> <div class="ttypography"><p>Fastest editorial I have ever seen!</p></div> </div> </div> <div class="reply info"> <a class="comment-601956 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601956 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601956"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601960" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601960" href="?#comment-601960" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601960" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601960" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601960"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces, I don't have any idea how to approach problems like Div2.D/Div1.B, can someone give me an advice? I am not sure what should I learn first in order to be able to come with a solution to this problem. Thanks :)</p></div> </div> </div> <div class="reply info"> <a class="comment-601960 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601960 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601960"> <li> <div class="comment"> <table class="comment-table" commentId="602364" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 06:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602364" href="?#comment-602364" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602364" class="CommentVoteFrame" data-commentRating="3" 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: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-602364"> <div class="moveup"> <div class="ttypography"><p>From my experience, Div 2 D tends to vary quite bit. I think the best way to go about it is to just keep on practicing a bunch of div 2 D, and look at editorials if you don't quite understand. Also, nice profile picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602364"> <li> <div class="comment"> <table class="comment-table" commentId="602461" commentParentId="602364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602461" href="?#comment-602461" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602364" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602461" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602461" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602461"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, I will keep practicing then :D. PS: I also like your picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602461 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602461 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602461"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602499" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602499" href="?#comment-602499" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602499" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602499"> <div class="moveup"> <div class="ttypography"><p>Well from my experience, it appears atleast one of C/D almost always involves graphs and/or DP. I'd recommend first learning all about graphs, especially some important techniques like DFS, BFS, multi-source BFS, SCC, bridges, cut-vertices etc.[Graphs are really awesome :] Then later move on to DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-602499 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602499 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602499"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604120" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 16:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604120" href="?#comment-604120" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604120" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604120"> <div class="moveup"> <div class="ttypography"><p>IMO you should first learn a little advanced algorithms and data structures and etc., also solve-up contests and past ones, i say the best way is to take virtual contests and then solve the rest of the problems excluding the cases you full the contest :). Also solve Div2.E after the contests, it's fine if you cant solve them, just take your time and try your best then go to editorial and make sure you fully understand the editorial and the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604120"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601962" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601962" href="?#comment-601962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601962" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-118" 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;">-118</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601962"> <div class="moveup"> <div class="ttypography"><p>i think it is better to provide codes instead of stories</p></div> </div> </div> <div class="reply info"> <a class="comment-601962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601962"> <li> <div class="comment"> <table class="comment-table" commentId="601995" commentParentId="601962"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601995" href="?#comment-601995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601995" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601995"> <div class="moveup"> <div class="ttypography"><p>That's why the button showing number of solves next to a problem exists. Click on that and you can see many codes and sort by speed, code length, etc.</p></div> </div> </div> <div class="reply info"> <a class="comment-601995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601995"> <li> <div class="comment"> <table class="comment-table" commentId="601999" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601999" href="?#comment-601999" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601999" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-30" 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;">-30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601999"> <div class="moveup"> <div class="ttypography"><p>I know that, But I want to see the code of the explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-601999 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601999 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601999"> <li> <div class="comment"> <table class="comment-table" commentId="602002" commentParentId="601999"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602002" href="?#comment-602002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601999" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602002" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602002"> <div class="moveup"> <div class="ttypography"><p>Wtf does that mean. Every code is most likely some variation of the explanation if it passed...</p></div> </div> </div> <div class="reply info"> <a class="comment-602002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602002"> <li> <div class="comment"> <table class="comment-table" commentId="602006" commentParentId="602002"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602006" href="?#comment-602006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602002" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602006" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-55" 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;">-55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602006"> <div class="moveup"> <div class="ttypography"><p>No</p></div> </div> </div> <div class="reply info"> <a class="comment-602006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602006"> <li> <div class="comment"> <table class="comment-table" commentId="602113" commentParentId="602006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602113" href="?#comment-602113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602113" class="CommentVoteFrame" data-commentRating="20" 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: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-602113"> <div class="moveup"> <div class="ttypography"><p>Yes</p></div> </div> </div> <div class="reply info"> <a class="comment-602113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602113"> <li> <div class="comment"> <table class="comment-table" commentId="602122" commentParentId="602113"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602122" href="?#comment-602122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602113" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602122" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" 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;">-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-602122"> <div class="moveup"> <div class="ttypography"><p>No is no</p></div> </div> </div> <div class="reply info"> <a class="comment-602122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602122"> <li> <div class="comment"> <table class="comment-table" commentId="602331" commentParentId="602122"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602331" href="?#comment-602331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602331" class="CommentVoteFrame" data-commentRating="41" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602331"> <div class="moveup"> <div class="ttypography"><p>Dumb is dumb</p></div> </div> </div> <div class="reply info"> <a class="comment-602331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602331"> <li> <div class="comment"> <table class="comment-table" commentId="602624" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 15:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602624" href="?#comment-602624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602624" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" 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;">-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-602624"> <div class="moveup"> <div class="ttypography"><p>Who is dumb there?</p></div> </div> </div> <div class="reply info"> <a class="comment-602624 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602624 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602624"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604121" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:02">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604121" href="?#comment-604121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604121" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604121"> <div class="moveup"> <div class="ttypography"><p>BABA IS YOU</p></div> </div> </div> <div class="reply info"> <a class="comment-604121 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604121 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604121"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604142" commentParentId="604121"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604142" href="?#comment-604142" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604142" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604142"> <div class="moveup"> <div class="ttypography"><p>Who is BABA?</p></div> </div> </div> <div class="reply info"> <a class="comment-604142 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604142 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604142"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604648" commentParentId="604142"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Suleyman.A" style="position: relative;"> <img src='https://userpic.codeforces.org/82791/avatar/fc8479c7406b79a3.jpg'/> </a> <div><a href="/profile/Suleyman.A" title="Expert Suleyman.A" class="rated-user user-blue">Suleyman.A</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604648" href="?#comment-604648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604142" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604648" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="82791" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604648"> <div class="moveup"> <div class="ttypography"><p>He is husband of your mother</p></div> </div> </div> <div class="reply info"> <a class="comment-604648 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604648 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604648"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602019" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602019" href="?#comment-602019" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602019" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602019"> <div class="moveup"> <div class="ttypography"><p>Its always better if editorial provides code or snippet about their approach</p></div> </div> </div> <div class="reply info"> <a class="comment-602019 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602019 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602019"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rajiv_kale" style="position: relative;"> <img src='https://userpic.codeforces.org/758545/avatar/575c69bbc5b5a715.jpg'/> </a> <div><a href="/profile/rajiv_kale" title="Newbie rajiv_kale" class="rated-user user-gray">rajiv_kale</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601975" href="?#comment-601975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601975" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601975" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="758545" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601975"> <div class="moveup"> <div class="ttypography"><p>Good editorial. I especially liked those behind stories.</p></div> </div> </div> <div class="reply info"> <a class="comment-601975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601975"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601992" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601992" href="?#comment-601992" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601992" class="CommentVoteFrame" data-commentRating="8" 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;">+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-601992"> <div class="moveup"> <div class="ttypography"><p>My E looks very different, now I'm wondering if it's correct.</p><p>Let's focus only on one big strongly connected component. For each vertex $$$V$$$ all the vertices which point to $$$V$$$ are ordered in a path. So, maybe it's possible to somehow form a cycle from all the vertices from the SCC. Let's take any vertex $$$V$$$. Now, from all the vertices which point to the $$$V$$$ let's take the last one on this path, let's call it $$$U$$$. Fix $$$U$$$ before $$$V$$$ on this cycle. Now, in the same manner, find a vertex that will be before $$$U$$$. And so on until we have a full cycle. My guess is that it's correct and that after this process which vertex points to some interval on the cycle which starts in this vertex. With such a form of the graph, we can easily calculate the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-601992 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601992 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601992"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602013" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602013" href="?#comment-602013" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602013" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-62" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-602013"> <div class="moveup"> <div class="ttypography"><p>Im not gonna lie but div2 was not interesting at all, problems D and E just required some basic observation. I hope future rounds require some more algorithmic skills to solve D and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-602013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602013"> <li> <div class="comment"> <table class="comment-table" commentId="602039" commentParentId="602013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602039" href="?#comment-602039" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602039" class="CommentVoteFrame" data-commentRating="100" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+100</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602039"> <div class="moveup"> <div class="ttypography"><p>How come did you only solve A then?</p></div> </div> </div> <div class="reply info"> <a class="comment-602039 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602039 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602039"> <li> <div class="comment"> <table class="comment-table" commentId="602102" commentParentId="602039"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602102" href="?#comment-602102" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602039" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602102" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-40" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602102"> <div class="moveup"> <div class="ttypography"><p>The point is not how many problems I solved or not but about the quality of problems, pls dont divert issues like this. (btw that submission to A is after contest :p)</p></div> </div> </div> <div class="reply info"> <a class="comment-602102 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602102 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602102"> <li> <div class="comment"> <table class="comment-table" commentId="602128" commentParentId="602102"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602128" href="?#comment-602128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602102" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602128" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602128"> <div class="moveup"> <div class="ttypography"><p>OK, I'm sorry.</p><p>Well, I thought they were good :D. It's kinda subjective. Who's to say &quot;making observations&quot; is worse than &quot;algorithmic skills&quot;? I don't think it's so much about &quot;quality of problems&quot; than &quot;style of problems&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-602128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602128"> <li> <div class="comment"> <table class="comment-table" commentId="602144" commentParentId="602128"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602144" href="?#comment-602144" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602144" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602144"> <div class="moveup"> <div class="ttypography"><p>I agree it's about style problems and I also liked the problems today. However I do agree with <a class="rated-user user-black" href="/profile/bored69" title="Unrated, bored69">bored69</a> that imo too many problems are extremely short to code while relying solely on observation. While I know many people enjoy the short to code problems, it is called _code_forces after all, so I think the solution should be longer than 10 lines to solve the problem, and I would enjoy getting to use some standard algorithms more often as long as the problem is still not straight application</p></div> </div> </div> <div class="reply info"> <a class="comment-602144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602144"> <li> <div class="comment"> <table class="comment-table" commentId="602407" commentParentId="602144"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lessmeaning" style="position: relative;"> <img src='https://userpic.codeforces.org/400632/avatar/4aeb556dedbc357a.jpg'/> </a> <div><a href="/profile/lessmeaning" title="Master lessmeaning" class="rated-user user-orange">lessmeaning</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602407" href="?#comment-602407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602144" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602407" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="400632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602407"> <div class="moveup"> <div class="ttypography"><p>Another Radewoosh's pawn</p></div> </div> </div> <div class="reply info"> <a class="comment-602407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602407"> <li> <div class="comment"> <table class="comment-table" commentId="602903" commentParentId="602407"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602903" href="?#comment-602903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602407" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602903" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602903"> <div class="moveup"> <div class="ttypography"><p>Maybe Radewoosh is my pawn ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-602903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602903"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602017" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602017" href="?#comment-602017" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602017" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602017"> <div class="moveup"> <div class="ttypography"><p>In Div 2-D explanation, I am not able to understand e-l+m part. Can someone help? </p></div> </div> </div> <div class="reply info"> <a class="comment-602017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602017"> <li> <div class="comment"> <table class="comment-table" commentId="602185" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602185" href="?#comment-602185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602185" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602185"> <div class="moveup"> <div class="ttypography"><p>The key construction in the editorial is that for every leaf i, the edge between i and its parent is xor(path(root,parent(i))). This construction guarantees different weights with one exception, what if multiple leaves have same parent? In that case we'll have only one extra distinct weight for all leaves with a common parent. So instead of including weights for all the leaves, we'll include weights only for their parents. Hence, first assume all edges as distinct and include them all(e) , then remove all leaves(l) and finally add those parents (which are non-leaf nodes with atleast one child as leaf (m)). So, we get e-l+m.</p></div> </div> </div> <div class="reply info"> <a class="comment-602185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602185"> <li> <div class="comment"> <table class="comment-table" commentId="602260" commentParentId="602185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602260" href="?#comment-602260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602185" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602260"> <div class="moveup"> <div class="ttypography"><p>I checked your solution. I am having some doubts. 1- Why did you choose your node as the vertex with a maximum degree? 2- The minimum f condition says if only odd paths are there, the minimum f is 1. forex. like 1--2--3--4(-- is an edge), how only one number can ensure bitwise XOR of 0?</p></div> </div> </div> <div class="reply info"> <a class="comment-602260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602260"> <li> <div class="comment"> <table class="comment-table" commentId="602286" commentParentId="602260"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602286" href="?#comment-602286" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602260" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602286" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602286"> <div class="moveup"> <div class="ttypography"><ol> <li>I had a different approach when I started coding, so i start with that node with maximum degre. In my approach, the necessary condition is that root node should not be leaf, if it is I'll not count one leaf in my dfs leading to a wrong answer.</li> <li>Minimum condition for f is, all leaf nodes should be at a distance of same parity from root, so that every pair of leaves are separated by even no. Of edges.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-602286 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602286 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602286"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602209" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602209" href="?#comment-602209" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602209" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602209"> <div class="moveup"> <div class="ttypography"><p>What about the case when edges with same weight are counted twice? In the picture Observation 3, the edges (1)-(2) and (2)-(6) should have the same weight. But the formula will count them as separate weights. Can someone please explain&gt;</p></div> </div> </div> <div class="reply info"> <a class="comment-602209 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602209 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602209"> <li> <div class="comment"> <table class="comment-table" commentId="602232" commentParentId="602209"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:52">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602232" href="?#comment-602232" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602209" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602232" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602232"> <div class="moveup"> <div class="ttypography"><p>No, it won't be counted twice. edges 1-2 and 2-6 are first removed by subtracting l (e-l) and then added once for their common parent 2(non-leaf node with 2 leaves) through m (e-l+m)</p></div> </div> </div> <div class="reply info"> <a class="comment-602232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602232"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602029" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaaven" style="position: relative;"> <img src='https://userpic.codeforces.org/851917/avatar/442eaf7f5f3f896b.jpg'/> </a> <div><a href="/profile/vaaven" title="Master vaaven" class="rated-user user-orange">vaaven</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602029" href="?#comment-602029" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602029" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="851917" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602029"> <div class="moveup"> <div class="ttypography"><p>Thank you for interesting and hard problems, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a>!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-602029 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602029 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602029"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602042" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602042" href="?#comment-602042" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602042" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602042" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602042"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1338/problem/B" title="Codeforces Round 633 (Div. 1)">1338B - Edge Weight Assignment</a> Dont get it how the construction works at all. Should't there be some recursion as we do a dfs? How/where do we start, and what to do in &quot;each step&quot;, assuming there are steps?</p></div> </div> </div> <div class="reply info"> <a class="comment-602042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602042"> <li> <div class="comment"> <table class="comment-table" commentId="602203" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AdsT" style="position: relative;"> <img src='https://userpic.codeforces.org/639570/avatar/f12b9c2694f9e204.jpg'/> </a> <div><a href="/profile/AdsT" title="Expert AdsT" class="rated-user user-blue">AdsT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602203" href="?#comment-602203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602203" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="639570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602203"> <div class="moveup"> <div class="ttypography"><p>I agree, everyone seemed to have just done the same thing, take one from the back and one from the front, I just am not able to prove this. How do I come to this conclusion?</p></div> </div> </div> <div class="reply info"> <a class="comment-602203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602203"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602348" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602348" href="?#comment-602348" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602348" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602348"> <div class="moveup"> <div class="ttypography"><p>This is a way that I came up with to always satisfy 3 distinct colors for every tree.</p><p>Choose a leaf (called $$$u$$$) and choose the connected node with this leaf (called $$$r$$$ and obviously this node won't be a leaf, as $$$n &gt;= 3$$$) as the root.</p><p>What we are going to construct is we are trying to make: $$$ xor(path(r, v)) = xor(path(r, u)) $$$ for every leaf $$$v$$$. Because when $$$ xor(path(r, v)) = xor(path(r, u)) $$$ then $$$ xor(path(r, v_1)) = xor(path(r, v_2)) ( = xor(path(r, u)))$$$ for every pair of leaves.</p><p>We have $$$xor(path(r, v_1)) = xor(path(r, v_2)) $$$ $$$\Leftrightarrow (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_1))) = (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_2)))$$$ $$$\Leftrightarrow xor(path(lca(v_1, v_2), v_1)) = xor(path(lca(v_1, v_2), v_2)) \Rightarrow$$$ Satisfy the condition</p><p>So here is what I do:</p> <ol> <li>Let the edge between $$$r$$$ and $$$u$$$ have weight $$$1$$$.</li> <li>We dfs from $$$r$$$, save the prefix $$$xor$$$ value from $$$r$$$ to the node $$$p$$$ we are at and dfs to node children $$$v$$$ of $$$p$$$:</li> </ol> <ul> <li>If $$$v$$$ is a leaf, then we need to assign this edge so that the prefix $$$xor$$$ value will be equal to $$$1$$$ ($$$ = xor(path(r, u))$$$).</li> <li>If $$$v$$$ is not a leaf, then we assign $$$2$$$ to that edge. Why? Because we need to get rid of the case when the prefix $$$xor$$$ value at node $$$p$$$ (parent of leaf $$$v$$$, for example) is equal to $$$1$$$ ($$$ = xor(path(r, u))$$$) and whatever we assign $$$edge(p, v)$$$ we cannot make the prefix $$$xor$$$ value at leaf $$$v$$$ equal to $$$1$$$ anymore.</li> </ul><p>P/s: Ask me anything that you may not understand ^^. </p></div> </div> </div> <div class="reply info"> <a class="comment-602348 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602348 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602348"> <li> <div class="comment"> <table class="comment-table" commentId="602440" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602440" href="?#comment-602440" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602440" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602440"> <div class="moveup"> <div class="ttypography"><p>Thanks!</p><p>Now I think the key observation to come up with all of this is the parity of distances of three leafs.</p><p>$$$parity(dist(l1,l2)) \oplus parity(dist(l1,l3)) = parity(dist(l2,l3))$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-602440 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602440 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602440"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603442" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603442" href="?#comment-603442" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603442" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603442"> <div class="moveup"> <div class="ttypography"><p>I didnt get the part where you assign 2 to the edge that is not a leaf.</p></div> </div> </div> <div class="reply info"> <a class="comment-603442 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603442 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603442"> <li> <div class="comment"> <table class="comment-table" commentId="603446" commentParentId="603442"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603446" href="?#comment-603446" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603442" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603446"> <div class="moveup"> <div class="ttypography"><p>Consider all the edges which not connect any leaf are assigned $$$2$$$, then all the prefix $$$xor$$$ value at node $$$p$$$ (not a leaf) will be either $$$...000$$$ or $$$...010$$$. So when we go to a leaf we can assign a possible value to make the prefix $$$xor$$$ equal to $$$...001$$$. </p><p>Suppose we don't assign $$$2$$$ but $$$1$$$ or $$$3$$$ then there will be the case when at node $$$p$$$ (not a leaf but have a leaf child) the prefix $$$xor$$$ may be $$$...001$$$ and go to node $$$v$$$ (the leaf child of $$$p$$$) whether we assign the edge $$$1$$$, $$$2$$$ or $$$3$$$ then the prefix $$$xor$$$ can't be $$$...001$$$ anymore.</p><p>Sorry for my bad English !</p></div> </div> </div> <div class="reply info"> <a class="comment-603446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603446"> <li> <div class="comment"> <table class="comment-table" commentId="603451" commentParentId="603446"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603451" href="?#comment-603451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603446" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603451" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603451"> <div class="moveup"> <div class="ttypography"><p>Thanks to your quick reply,I am able to understand it.Can you please suggest some resources or something that would help me in solving problem cause' I am only able to solve upto problem c everytime?</p></div> </div> </div> <div class="reply info"> <a class="comment-603451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603451"> <li> <div class="comment"> <table class="comment-table" commentId="603456" commentParentId="603451"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603456" href="?#comment-603456" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603451" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603456" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603456"> <div class="moveup"> <div class="ttypography"><p>My suggestions: Solve problems and reflect upon what you have done wrong ... or what's observation you missed (And note them back obviously) ... or new algorithms (search and read for them and do 3 — 5 problems about that topic). Sometimes algorithm have signs, try to see that.</p><p>P/s: It's my own opinion anyway. Good luck &lt;3.</p></div> </div> </div> <div class="reply info"> <a class="comment-603456 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603456 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603456"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606855" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Darooha" style="position: relative;"> <img src='https://userpic.codeforces.org/27157/avatar/c4be2a4212ec87ed.jpg'/> </a> <div><a href="/profile/Darooha" title="Pupil Darooha" class="rated-user user-green">Darooha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606855" href="?#comment-606855" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606855" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="27157" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-606855"> <div class="moveup"> <div class="ttypography"><p>To everybody: The editorial has this update. It makes the problem much simpler:</p><p>(Update) There is an another way to approach, provided by Darooha.</p><p>If you label vertices instead of edges where all leaves have same label and none of neighbors have same label, then you can consider edge weight as xor of two vertices' labels, so this is basically equivalent to original problem.</p><p>Now for minimum, you can see that labelling 0 to leaves, and 1,2 to non-leaves are enough, so you can prove minimum value of f is at most 3. In same manner, you can try parity checking to check if f value can be 1 or not.</p><p>For maximum, assign 0 to all leaves and assign all different values(21,22,...) to non-leaf vertices, then you can see all edge weights(except leaves connected to same vertex) are different.</p></div> </div> </div> <div class="reply info"> <a class="comment-606855 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606855 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606855"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rojansudev700" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rojansudev700" title="Newbie rojansudev700" class="rated-user user-gray">rojansudev700</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602066" href="?#comment-602066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1236502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602066"> <div class="moveup"> <div class="ttypography"><p>Can anybody please explain problem A and its editorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-602066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602066"> <li> <div class="comment"> <table class="comment-table" commentId="602098" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602098" href="?#comment-602098" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602098"> <div class="moveup"> <div class="ttypography"><p>You may refer to the picture in the editorial. In this picture, if you put the red one in, you will find there is only one way to fill it( also described in the picture). Hence, since there are N different ways for putting the red one in, the answer is simply N.</p></div> </div> </div> <div class="reply info"> <a class="comment-602098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602098"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602157" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Apr/12/2020 21:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602157" href="?#comment-602157" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602157" 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-602157"> <div class="moveup"> <div class="ttypography"><p>Consider you want to find the answer for shape with size N. Let's say you put a Vertical diamond initially then places of all other diamonds are decided. So this is 1 way to put diamonds.</p><p>The other way is to put two horizontal diamonds on top left and bottom left and then we are have to find ways to puts diamonds in a shape of size N-1.</p><p>Ans(i) = 1 + Ans(i-1) <br /> {1 for the way in which vertical diamond is placed on the leftmost position}</p><p>Ans(i) = 1 + Ans(i-1) = i, given ans(1) =1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602157"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602093" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bayweiheng" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bayweiheng" title="Grandmaster bayweiheng" class="rated-user user-red">bayweiheng</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602093" href="?#comment-602093" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602093" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="533715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602093"> <div class="moveup"> <div class="ttypography"><p>In Div1E, How can we calculate the contribution from vertices with no indegree? If v has no indegree, then dis(u,v) is known but how do we find dis(v,u)? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-602093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602093"> <li> <div class="comment"> <table class="comment-table" commentId="602110" commentParentId="602093"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602110" href="?#comment-602110" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602093" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602110" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602110"> <div class="moveup"> <div class="ttypography"><p>If $$$u$$$ has no in-degree then $$$dis(u,v)=1, dis(v,u)=614n$$$ for all $$$u\neq v$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602110 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602110 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602110"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602145" href="?#comment-602145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602145" 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="602145" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602145"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">E intuition?</b><div class="spoiler-content" style="display: none;"><p>Assume that all nodes have positive in-degree. Then we can arrange the nodes in a cycle $$$c_0,c_1,\ldots, c_{n-1}$$$ such that $$$c_i$$$ has edges to $$$c_{i+1},c_{i+2},\ldots,c_{(i+out(i))\pmod{n}}$$$ where $$$out(i)$$$ denotes the out-degree of node $$$c_i$$$. To find this cycle, start with any vertex $$$x$$$ and topologically sort $$$in(x)$$$. Then repeat with the last node of $$$in(x)$$$ (with respect to the sorted order).</p><p>For all $$$i$$$, $$$out(i)&gt;0$$$ and $$$out(i)\le out((i+1)\pmod{n})+1$$$. Suppose that $$$i&lt;j$$$. Then $$$out(i)+i\le out(j)+j$$$ and the distance from $$$c_j$$$ to $$$c_i$$$ is three iff $$$out(i)+i=out(j)+j$$$. Otherwise, it's one or two.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-602145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602145"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602151" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misqwerty" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/misqwerty" title="Newbie misqwerty" class="rated-user user-gray">misqwerty</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602151" href="?#comment-602151" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602151" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="727011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602151"> <div class="moveup"> <div class="ttypography"><p>Do anyone else other than me recognize this submission as a hack for a hack and there were two successful hacking attempts. That's a <strong>cheat</strong>. <a href="/contest/1339/submission/76401969" title="Submission 76401969 by SIBshaan">76401969</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602151 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602151 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602151"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602165" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602165" href="?#comment-602165" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602165" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602165"> <div class="moveup"> <div class="ttypography"><p>how to find editorial in english for Atcoder Begginer contest 162 on their website it's in japanese..</p></div> </div> </div> <div class="reply info"> <a class="comment-602165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602165"> <li> <div class="comment"> <table class="comment-table" commentId="602170" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:39">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602170" href="?#comment-602170" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602170" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602170"> <div class="moveup"> <div class="ttypography"><p>Pay attention to the red line written on the first page of the Japanese editorial .</p></div> </div> </div> <div class="reply info"> <a class="comment-602170 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602170 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602170"> <li> <div class="comment"> <table class="comment-table" commentId="602195" commentParentId="602170"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602195" href="?#comment-602195" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602170" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602195" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602195"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602195 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602195 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602195"> <li> <div class="comment"> <table class="comment-table" commentId="602248" commentParentId="602195"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602248" href="?#comment-602248" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602195" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602248" 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-602248"> <div class="moveup"> <div class="ttypography"><p>I've solved A,B,C,D if you want, i can tell u how to solve them</p></div> </div> </div> <div class="reply info"> <a class="comment-602248 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602248 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602248"> <li> <div class="comment"> <table class="comment-table" commentId="602255" commentParentId="602248"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602255" href="?#comment-602255" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602248" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602255" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602255" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602255"> <div class="moveup"> <div class="ttypography"><p>please tell me how you solved D</p></div> </div> </div> <div class="reply info"> <a class="comment-602255 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602255 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602255"> <li> <div class="comment"> <table class="comment-table" commentId="602270" commentParentId="602255"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602270" href="?#comment-602270" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602255" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602270" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602270" 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-602270"> <div class="moveup"> <div class="ttypography"><p>So you gonna fix i and k such that S[i] != S[k]. So in the range [i + 1, k — 1] you should find the number of characters C different from S[i] as well as S[j]. So, for example, if S[i] = 'R' and S[k] = 'G', C = 'B'. So these different characters can be found using segment tree, maybe there is other method too. Also you should check for the second condition, if (k — i) % 2 == 0 and S[(i + k) / 2] == c, you gonna decrement that number by one.</p></div> </div> </div> <div class="reply info"> <a class="comment-602270 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602270 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602270"> <li> <div class="comment"> <table class="comment-table" commentId="602272" commentParentId="602270"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602272" href="?#comment-602272" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602270" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602272" 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-602272"> <div class="moveup"> <div class="ttypography"><p>That's my solution, but I think there is a better solution described in the following video: <a href="https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s">https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602272"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602172" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602172" href="?#comment-602172" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602172" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602172"> <div class="moveup"> <div class="ttypography"><p>Btw, why ask this here xD</p></div> </div> </div> <div class="reply info"> <a class="comment-602172 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602172 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602172"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602167" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602167" href="?#comment-602167" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602167" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602167"> <div class="moveup"> <div class="ttypography"><p>Could someone elaborate a bit more the intuition behind Div1D and how to implement it?</p></div> </div> </div> <div class="reply info"> <a class="comment-602167 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602167 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602167"> <li> <div class="comment"> <table class="comment-table" commentId="602265" commentParentId="602167"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602265" href="?#comment-602265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602167" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602265" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602265" class="CommentVoteFrame" data-commentRating="42" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+42</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602265"> <div class="moveup"> <div class="ttypography"><p>I approached this problem by considering what happens if we only consider the minimum connected subgraph containing the answer, where the answer is the set of nodes $$$S$$$ that form the nested rubber bands. First, consider each $$$v\in S$$$ as a circle, so we have $$$|S|$$$ nested circles. The other vertices of this minimum connected subgraph must contribute to connecting two or more circles, and we can consider them as line segments. </p><p>Colour the line segments red and the circles blue. Then, we'll see that the red vertices lie on a path, because we can trace out a path in this alternate representation of the tree. Furthermore, the blue vertices form an independent set, and each is adjacent to at least one red vertex.</p><p>DP states:</p><p>For each state, I suppose that the red vertices lie on a path in the subtree rooted at u with one endpoint at u.</p> <ul> <li><p>take[u] = number of blue vertices if u is blue</p></li> <li><p>skip[u] = number of blue vertices if u is red</p></li> </ul><p>DP transitions:</p> <ul> <li><p><code>take[u] = max(1 + skip[child])</code>. Since we're interested in a path, we take the max.</p></li> <li><p><code>skip[u] = max(#children-1 + max(take[child], skip[child]))</code>. If we colour u red, then we can colour all its uncoloured neighbours blue, but we still want to be able to choose for the next node in the path.</p></li> </ul><p>To get the answer, consider a path rooted at u. We need to know the best two values of <code>take[child]</code> and <code>max(take[child], skip[child])</code> to find the answer for such a path.</p><p>I'm sure you could fit the dp and get the solution in one dfs function, but here's my rather long and verbose code: <a href="https://codeforces.com/contest/1338/submission/76420228">https://codeforces.com/contest/1338/submission/76420228</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602265"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602182" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gouravmajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1380497/avatar/470f8f4adfac9b5d.jpg'/> </a> <div><a href="/profile/gouravmajee" title="Newbie gouravmajee" class="rated-user user-gray">gouravmajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602182" href="?#comment-602182" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602182" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1380497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602182"> <div class="moveup"> <div class="ttypography"><p>this was my first contest :) I passed question 1. </p></div> </div> </div> <div class="reply info"> <a class="comment-602182 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602182 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602182"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602191" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aid" style="position: relative;"> <img src='https://userpic.codeforces.org/106240/avatar/ab90218e19d9e731.jpg'/> </a> <div><a href="/profile/aid" title="International Grandmaster aid" class="rated-user user-red">aid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602191" href="?#comment-602191" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602191" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="106240" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602191"> <div class="moveup"> <div class="ttypography"><p>$$$O(n^2\log(n))$$$ can be squeezed in E: <a href="/contest/1338/submission/76419686" title="Submission 76419686 by aid">76419686</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-602191 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602191 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602191"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602210" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cdc.biobot" style="position: relative;"> <img src='https://userpic.codeforces.org/152957/avatar/23e3d83914fae0f6.jpg'/> </a> <div><a href="/profile/cdc.biobot" title="Newbie cdc.biobot" class="rated-user user-gray">cdc.biobot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602210" href="?#comment-602210" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602210" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602210" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="152957" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602210"> <div class="moveup"> <div class="ttypography"><p>I beg your pardon, but I think problem statement of div2A should have been a bit clearer in explaining the term 'covering differently'. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-602210 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602210 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602210"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602211" href="?#comment-602211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602211" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602211"> <div class="moveup"> <div class="ttypography"><p>In Div2 D for finding the maximum f value, what is the proof that there is no other construction possible that can possibly have more distinct weights? For example, consider a tree with the non-leaf nodes having degree 4. In the observation 3 picture, we can add to node 2, a replica structure of its child node 3. That will make node 2's degree 4. How to prove for this case(and in general) that the maximum value of f will not exceed e-l+m?</p></div> </div> </div> <div class="reply info"> <a class="comment-602211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602211"> <li> <div class="comment"> <table class="comment-table" commentId="602241" commentParentId="602211"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602241" href="?#comment-602241" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602211" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602241" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602241"> <div class="moveup"> <div class="ttypography"><p>Because that's the upper bound of the value.</p><p>Every edge that isn't adjacent to a leaf doesn't matter. Edges for leaves that are adjacent to the same non-leaf vertex need to be equal. That can be counted as in the editorial because — (leaves — non-leaf vertex adjacent to a leaf) is exactly the number of edges to leaves that are free to receive values.</p></div> </div> </div> <div class="reply info"> <a class="comment-602241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602241"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602221" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602221" href="?#comment-602221" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602221" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602221"> <div class="moveup"> <div class="ttypography"><p>hi..what is the maximum time in which it's good to solve div2 — A and B.. because i'm practicing only DIV2 A and B question in virtual contest..and still took more than 1 h to solve both...some time i failed to solve B.. Thanks in advance..</p></div> </div> </div> <div class="reply info"> <a class="comment-602221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602221"> <li> <div class="comment"> <table class="comment-table" commentId="602497" commentParentId="602221"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602497" href="?#comment-602497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602221" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602497"> <div class="moveup"> <div class="ttypography"><p>See this round was tough, but I think top coders take max 15 min for both, at my rating I think even 30 mins would be fine and for you, 45-60 min is the max you should ideally take</p></div> </div> </div> <div class="reply info"> <a class="comment-602497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602497"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602236" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Muhammad98" style="position: relative;"> <img src='https://userpic.codeforces.org/697747/avatar/2c13087bfd195af6.jpg'/> </a> <div><a href="/profile/Muhammad98" title="Specialist Muhammad98" class="rated-user user-cyan">Muhammad98</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602236" href="?#comment-602236" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="697747" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602236"> <div class="moveup"> <div class="ttypography"><p>The only Div2A that I couldn't solve during the round XD</p></div> </div> </div> <div class="reply info"> <a class="comment-602236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602236"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602238" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602238" href="?#comment-602238" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602238" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602238"> <div class="moveup"> <div class="ttypography"><p>Nice editorial and pictures! <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> One suggestion: It'll be easier to read d1E if you use lowercase letters for vertices and upper case letters for sets.</p></div> </div> </div> <div class="reply info"> <a class="comment-602238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602238"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gjaiswal108" style="position: relative;"> <img src='https://userpic.codeforces.org/756634/avatar/f398cd162ff7d60f.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/gjaiswal108" title="Expert gjaiswal108" class="rated-user user-blue">gjaiswal108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602251" href="?#comment-602251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602251" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756634" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602251"> <div class="moveup"> <div class="ttypography"><p><code>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this</code></p><p>Can anyone tell me what is meaning of OEIS in the story of D2E ?</p></div> </div> </div> <div class="reply info"> <a class="comment-602251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602251"> <li> <div class="comment"> <table class="comment-table" commentId="602259" commentParentId="602251"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/blitzitout" style="position: relative;"> <img src='https://userpic.codeforces.org/505681/avatar/39b2976ffc156007.jpg'/> </a> <div><a href="/profile/blitzitout" title="Expert blitzitout" class="rated-user user-blue">blitzitout</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602259" href="?#comment-602259" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602251" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602259" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602259" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="505681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602259"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/">This</a> is where you can find insights/recurrences of random sequences.</p></div> </div> </div> <div class="reply info"> <a class="comment-602259 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602259 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602259"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602252" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T-REXX" style="position: relative;"> <img src='https://userpic.codeforces.org/455170/avatar/f7f08af680e3156f.jpg'/> </a> <div><a href="/profile/T-REXX" title="Pupil T-REXX" class="rated-user user-green">T-REXX</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602252" href="?#comment-602252" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602252" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="455170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602252"> <div class="moveup"> <div class="ttypography"><p>I tried solving div2C by iterating through the array, whenever a[i]&gt;a[i+1] I added to all j=i+1 and j&lt;n lowest power of 2 possible to make it a[i]&lt;=a[i+1]. Lowest power was calculated using a vector of powers of 2. But it does not work, and I am unable to find out why. Can anyone help?</p></div> </div> </div> <div class="reply info"> <a class="comment-602252 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602252 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602252"> <li> <div class="comment"> <table class="comment-table" commentId="602471" commentParentId="602252"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bryceShakeair" style="position: relative;"> <img src='https://userpic.codeforces.org/872528/avatar/f8595cfd5dbfc474.jpg'/> </a> <div><a href="/profile/bryceShakeair" title="Specialist bryceShakeair" class="rated-user user-cyan">bryceShakeair</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602471" href="?#comment-602471" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602252" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602471" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872528" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602471"> <div class="moveup"> <div class="ttypography"><p>try 1 0 1 0 1 0 The optimal answer is x = 1 i.e. select indexes 2 , 4 ,6 you get 1 1 1 1 1 1 I hope that is clear </p></div> </div> </div> <div class="reply info"> <a class="comment-602471 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602471 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602471"> <li> <div class="comment"> <table class="comment-table" commentId="604684" commentParentId="602471"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604684" href="?#comment-604684" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602471" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604684" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604684"> <div class="moveup"> <div class="ttypography"><p>Thanks. </p></div> </div> </div> <div class="reply info"> <a class="comment-604684 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604684 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604684"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602282" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant_raja" style="position: relative;"> <img src='https://userpic.codeforces.org/742080/avatar/101f3740a4030218.jpg'/> </a> <div><a href="/profile/nishant_raja" title="Pupil nishant_raja" class="rated-user user-green">nishant_raja</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602282" href="?#comment-602282" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602282" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742080" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602282"> <div class="moveup"> <div class="ttypography"><p>Can anyone briefly explain the problem &quot;Powered Addition&quot;, I mean full approach and walk through an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-602282 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602282 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602282"> <li> <div class="comment"> <table class="comment-table" commentId="602498" commentParentId="602282"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jbs1jbs1jbs1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/jbs1jbs1jbs1" title="Specialist jbs1jbs1jbs1" class="rated-user user-cyan">jbs1jbs1jbs1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602498" href="?#comment-602498" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602282" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602498" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602498"> <div class="moveup"> <div class="ttypography"><p>My approach was as follows:</p><p>Let's say that the list is <code>[1, 7, 6, 5]</code>. We go through and we look at all the pairs <code>(a[i], a[i+1])</code>. We start with <code>(1,7)</code>. It satisfies the property of being non-decreasing, so we do nothing. Next, we go to <code>(7, 6)</code>. <code>6 &lt; 7</code>, meaning we have to add something to &quot;6&quot; to make it bigger. I assert (and will explain below the reason why), that it is possible and optimal to convert the &quot;6&quot; into a &quot;7&quot;. The list then becomes <code>[1, 7, 7, 5]</code>. Next, we look at the final pair <code>(7, 5)</code> and do the same: convert the &quot;5&quot; to a &quot;7&quot;, so that the final list becomes [1, 7, 7, 7].</p><p>When we convert a pair (a, b) to the pair (a, a), it means that we need to add some quantity (a-b) to it. If that quantity is 18, for example, then we can do this with 16 + 2 = 2^4 + 2^1. If that quantity is 15, we can do this with 2^0 + 2^1 + 2^2 + 2^3. In general, there is exactly one way to do the addition of distinct powers of 2 to get from one number to another.</p><p>You can find out which powers of 2 you need to add together by converting the difference into binary. The definition of binary is that where there is a &quot;1&quot; you can add the relevant power of 2.</p><p>In any case, I'm just saying that it is always <strong>possible</strong> to do this, and it doesn't matter what the exact powers of 2 are, you just need to know what the biggest power of 2 needed will be. This is because if you're using a bigger power of 2, for example 2^5, it means that seconds 1, 2, 3, 4, 5, 6 have already happened, so you could have, in the past, added 2^0, 2^1, 2^2, 2^3, 2^4 if you needed to do so.</p><p>The biggest power of 2 needed can be worked out by taking the logarithm base 2 of the difference, and then rounding down.</p><p>The code would then be something like this:</p> <pre><code>max_power_found = -1 for i in range(len(a) - 1): if a[i + 1] &lt; a[i]: difference = a[i] - a[i + 1] biggest_power = floor(log2(difference)) max_power_found = max(max_power_found, biggest_power) a[i + 1] = a[i] print(max_power_found + 1) </code></pre><p>Note that I initialise <code>max_power_found</code> to <code>-1</code> so that at the end, if nothing has happened because the array was already non-decreasing, it becomes <code>0</code> when you add 1.</p><p>Note also that even though we don't need to output the final array, I have the line <code>a[i + 1] = a[i]</code>. This is because the next pair needs to know about the change we just made.</p><p>There are <code>(n-1)</code> possible values of <code>i</code>, and for each one we do some constant time computation (logarithm base 2 is very fast), this is an O(n) solution.</p><p>Note that even if you didn't know about logarithms, you could probably do it very quickly because log2(10^5) is very small (though I haven't tested to make sure this doesn't TLE):</p> <pre><code>def biggest_power_needed(difference): # Outputs -1 if difference is 0. answer = -1 total = 0 while total &lt; difference: answer++ total += pow(2, answer) if total == difference: return answer else: return answer - 1 </code></pre><p>Again, we do <code>answer - 1</code> because we can use the smaller powers of 2 to increase it to exactly equal the difference.</p></div> </div> </div> <div class="reply info"> <a class="comment-602498 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602498 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602498"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shivamsaluja20" style="position: relative;"> <img src='https://userpic.codeforces.org/820036/avatar/92e6360dd7bc5c3d.jpg'/> </a> <div><a href="/profile/shivamsaluja20" title="Specialist shivamsaluja20" class="rated-user user-cyan">shivamsaluja20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602291" href="?#comment-602291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602291" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="820036" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602291"> <div class="moveup"> <div class="ttypography"><p>For the first time for problem A, it took me around 50 minutes to figure out and ironically that was the easiest one liner solution possible. Take the input and print it xD.</p></div> </div> </div> <div class="reply info"> <a class="comment-602291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EleCursity" style="position: relative;"> <img src='https://userpic.codeforces.org/388600/avatar/c667ca12cb3a5eb2.jpg'/> </a> <div><a href="/profile/EleCursity" title="Expert EleCursity" class="rated-user user-blue">EleCursity</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602292" href="?#comment-602292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602292" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="388600" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602292"> <div class="moveup"> <div class="ttypography"><p>Nice Editorial and nice problems. In <strong>div2E/div1C</strong> .I've found a strange pattern for the bits in the n-th triple . but I can't manage to code it during the contest. this is my code <a href="/contest/1339/submission/76432679" title="Submission 76432679 by EleCursity">76432679</a> .</p></div> </div> </div> <div class="reply info"> <a class="comment-602292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602297" href="?#comment-602297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602297"> <div class="moveup"> <div class="ttypography"><p>2D, I understand nothing, damn constructive problems and damn gap between C and D</p><p>&quot;Observation 1. You can prove that minimum value of f is at most 3, by following construction;&quot;</p><p>Well, how do we know there is no other construction where we would have 4 or more?</p><p>&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?</p><p>&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose</p></div> </div> </div> <div class="reply info"> <a class="comment-602297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602297"> <li> <div class="comment"> <table class="comment-table" commentId="602302" commentParentId="602297"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602302" href="?#comment-602302" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602297" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602302" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-602302"> <div class="moveup"> <div class="ttypography"><p>&quot;Well, how do we know there is no other construction where we would have 4 or more?&quot; The problem is asking for the minimum, there is a construction where $$$3$$$ is possible so the minimum is never greater than $$$3$$$</p><p>&quot;&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?&quot; Because we decided that that's how the construction should look like. Another example of a construction which would work is edges connecting a leaf having a weight of $$$2$$$ or $$$3$$$ depending on the parity leaf's depth and all other edges having a weight of $$$1$$$.</p><p>&quot;&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose&quot; Here's a proof: Notice that we can consider each bit separately and then an assignment works if the condition is satisfied for all bits. Let's say we choose numbers $$$a$$$ and $$$b$$$. If both $$$a$$$ and $$$b$$$ have some bit set to $$$1$$$ then that is the same as the $$$f=1$$$ case. If there is no bit which both $$$a$$$ and $$$b$$$ have set to 1 then that means that there is a bit which $$$a$$$ has set to $$$1$$$ and $$$b$$$ has set to $$$0$$$ and that there is a bit which $$$a$$$ has set to $$$0$$$ and $$$b$$$ has set to $$$1$$$, so each path needs to have an even number of both $$$a$$$ and $$$b$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602302 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602302 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602302"> <li> <div class="comment"> <table class="comment-table" commentId="602304" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 02:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602304" href="?#comment-602304" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602304" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602304"> <div class="moveup"> <div class="ttypography"><p>1-2) Oh, so it was about describing a generic technique of assigning values, not about the specific tree on the picture. Then it makes more sense</p><p>3) The confusing part here was that I thought it was about the number of a and b in the whole tree, not on the requested path, and didn't understand why.</p><p>I'll reread it with this in mind</p><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602304"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603392" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 02:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603392" href="?#comment-603392" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603392" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603392" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603392"> <div class="moveup"> <div class="ttypography"><p>I've got how we come up with f=3 from the comments</p><p>However I still don't understand the same part in the editorial &quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>On the picture we have a string of non-leaves, all of which have degree 3. And all the leaves obviously have degree 1 So following this statement we're supposed to have the same weights for every edge connecting a non-leaf to a leaf on the picture. However, this is not the case. </p></div> </div> </div> <div class="reply info"> <a class="comment-603392 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603392 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603392"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/feecIe6418" style="position: relative;"> <img src='https://userpic.codeforces.org/699680/avatar/da9b3b3e29a8fe7b.jpg'/> </a> <div><a href="/profile/feecIe6418" title="International Grandmaster feecIe6418" class="rated-user user-red">feecIe6418</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 03:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602320" href="?#comment-602320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602320" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="699680" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602320"> <div class="moveup"> <div class="ttypography"><p>Finally become master in this round. I like the problems! Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-602320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602334" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602334" href="?#comment-602334" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602334" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602334"> <div class="moveup"> <div class="ttypography"><p><strong>HELP! Please</strong></p><p>Hi, everyone! My friends has some trouble in his solutions, He has submitted this solution <a href="/contest/1339/submission/76367506" title="Submission 76367506 by zhouxiaolun">76367506</a> during the round, However, after the system pending test, He did not get an AC, but still the Pretest passed. The score for this problem was not added to my friends. He has submitted totally the same code just now, <a href="/contest/1339/submission/76438866" title="Submission 76438866 by zhouxiaolun">76438866</a>, and get an AC. Why did this happen? It has effected on my friends ratings, Where can I find the administor to solve the trouble? (sorry for my poor english)</p></div> </div> </div> <div class="reply info"> <a class="comment-602334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602334"> <li> <div class="comment"> <table class="comment-table" commentId="602339" commentParentId="602334"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iynaur87" style="position: relative;"> <img src='https://userpic.codeforces.org/561459/avatar/4516a52f8c97c0c2.jpg'/> </a> <div><a href="/profile/iynaur87" title="Candidate Master iynaur87" class="rated-user user-violet">iynaur87</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602339" href="?#comment-602339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602334" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602339" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="561459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602339"> <div class="moveup"> <div class="ttypography"><p>Weired. You can Send a message to <a href="https://codeforces.com/profile/MikeMirzayanov">https://codeforces.com/profile/MikeMirzayanov</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602339"> <li> <div class="comment"> <table class="comment-table" commentId="602345" commentParentId="602339"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602345" href="?#comment-602345" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602339" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602345" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602345"> <div class="moveup"> <div class="ttypography"><p>Thank you! You are so kind!</p></div> </div> </div> <div class="reply info"> <a class="comment-602345 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602345 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602345"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602341" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Raghu150999" style="position: relative;"> <img src='https://userpic.codeforces.org/714738/avatar/992860969ab6c84.jpg'/> </a> <div><a href="/profile/Raghu150999" title="Expert Raghu150999" class="rated-user user-blue">Raghu150999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602341" href="?#comment-602341" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602341" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714738" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602341"> <div class="moveup"> <div class="ttypography"><p>Great editorial. Thanks a lot!</p></div> </div> </div> <div class="reply info"> <a class="comment-602341 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602341 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602341"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602383" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aspiriner" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/aspiriner" title="Expert aspiriner" class="rated-user user-blue">aspiriner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602383" href="?#comment-602383" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602383" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1393907" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602383"> <div class="moveup"> <div class="ttypography"><p>in the div 2 B </p><p>i do not understand what the 'Sort the list, and make an oscillation centered on middle element like picture below.' means.</p><p>i just dont know how to sort it and what should i do in the next step.</p><p>please help me!</p></div> </div> </div> <div class="reply info"> <a class="comment-602383 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602383 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602383"> <li> <div class="comment"> <table class="comment-table" commentId="602411" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shisuko" style="position: relative;"> <img src='https://userpic.codeforces.org/554313/avatar/42772b63e4542d29.jpg'/> </a> <div><a href="/profile/Shisuko" title="Candidate Master Shisuko" class="rated-user user-violet">Shisuko</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602411" href="?#comment-602411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602411" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="554313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602411"> <div class="moveup"> <div class="ttypography"><p>Sort the elements in ascending order. Then you go smallest-&gt;largest-&gt;second smallest-&gt;second largest... and so on. If you draw it on paper, you can see that the gaps are always getting smaller because it's a subset of the previous gap.</p></div> </div> </div> <div class="reply info"> <a class="comment-602411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602411"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602415" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602415" href="?#comment-602415" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602415" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602415"> <div class="moveup"> <div class="ttypography"><p>Imagine the problem is the same, but differences between pairs must be non increasing instead of non decreasing ( | a_ i — a_i-1 | &gt;= | a_i-1 — a_i-2 | ). If we solve this, we can just reverse the answer and we will get an answer to the original problem. </p><p>Now, imagine we start with the biggest element to the left. What number should we add next to maximize their difference? The smallest element. So we add it. After that, what number not yet added would maximize the difference of the pair? The second biggest element, and it is not hard to see it will be smaller or equal than the first pair. If we continue to do this, we can get an answer.</p><p>So to build it we just sort the initial array and then build it in the following way: a[N] , a[1] , a[N-1] , a[2] , a[N-2] , a[3] ... </p><p>After this, don't forget to reverse the answer to solve the original problem. </p><p>Submission: <a href="/contest/1339/submission/76418078" title="Submission 76418078 by Diegogrc">76418078</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602415 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602415 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602415"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602445" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xD." style="position: relative;"> <img src='https://userpic.codeforces.org/918251/avatar/298a43e5c9cee8f5.jpg'/> </a> <div><a href="/profile/xD." title="Pupil xD." class="rated-user user-green">xD.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602445" href="?#comment-602445" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602445" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602445" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="918251" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602445"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/aspiriner" title="Pupil aspiriner">aspiriner</a> <strong>This picture may help you</strong> <img alt=" " src="/predownloaded/43/9a/439a03f6fa84e1a1c14509dbd3d5c4c88ee8d5a3.php" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-602445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602445"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602386" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misty1999" style="position: relative;"> <img src='https://userpic.codeforces.org/461973/avatar/bda2e09a046c8571.jpg'/> </a> <div><a href="/profile/misty1999" title="Specialist misty1999" class="rated-user user-cyan">misty1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602386" href="?#comment-602386" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602386" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="461973" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602386"> <div class="moveup"> <div class="ttypography"><p>First I thought maximal independent set in div1D, but got Wrong Answer on pretest 4.</p></div> </div> </div> <div class="reply info"> <a class="comment-602386 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602386 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602386"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuber_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/820815/avatar/9d558886908a602d.jpg'/> </a> <div><a href="/profile/cuber_coder" title="Master cuber_coder" class="rated-user user-orange">cuber_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602400" href="?#comment-602400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602400" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="820815" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602400"> <div class="moveup"> <div class="ttypography"><p>Great problemset, a beautifully written editorial, no queueforces, strong pretests and quick system testing makes it a wonderful round! Hope to participate in more rounds authored by you in future!</p><p>P.S. : my most special round till date since I finally reached CM !</p></div> </div> </div> <div class="reply info"> <a class="comment-602400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602400"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602404" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602404" href="?#comment-602404" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602404" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602404"> <div class="moveup"> <div class="ttypography"><p>can someone explain div2-C,i am not able to understand the editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-602404 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602404 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602404"> <li> <div class="comment"> <table class="comment-table" commentId="602437" commentParentId="602404"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602437" href="?#comment-602437" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602404" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602437" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602437"> <div class="moveup"> <div class="ttypography"><p>first of all find the max difference between any two number (O(n)). then you just need to count number of digits in it. which can be done using log2 of that difference. note: ceil function is to be used for ex: 2.5 would be rounded off to 3.</p><p>here's my code(which is actually someone else but I copied it and modified a little, but is self explanatory )</p><p><a href="https://codeforces.com/contest/1339/submission/76446573">https://codeforces.com/contest/1339/submission/76446573</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602437 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602437 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602437"> <li> <div class="comment"> <table class="comment-table" commentId="602494" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602494" href="?#comment-602494" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602494" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602494"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/FinalBoss_" title="Pupil FinalBoss_">FinalBoss_</a> Can you please explain why did you add 1 in log2(dis+1) ?</p><p>I guess dis is the max number required to add.Why +1 ?My first submission was same but i didnt add 1 it got wa.</p></div> </div> </div> <div class="reply info"> <a class="comment-602494 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602494 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602494"> <li> <div class="comment"> <table class="comment-table" commentId="602546" commentParentId="602494"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602546" href="?#comment-602546" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602494" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602546" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602546"> <div class="moveup"> <div class="ttypography"><p>yes dis is the max number required to add. log2(dis+1) is done because... we were asked to find 2^(x-1).</p><p>in case all numbers are equal and dis is 0 or if array is already increasing and dis is still 0, then log(0) becomes undefined. Now since we don't need actual value but ceiling of it so adding 1 to dis and then taking log will have same effect but also it will remove ambiguity of log(0).</p></div> </div> </div> <div class="reply info"> <a class="comment-602546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602546"> <li> <div class="comment"> <table class="comment-table" commentId="602650" commentParentId="602546"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602650" href="?#comment-602650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602546" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602650"> <div class="moveup"> <div class="ttypography"><p>Thanks, got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-602650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602650"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603609" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaibhavsingh100070" style="position: relative;"> <img src='https://userpic.codeforces.org/792197/avatar/6a8b6f989cc93e7d.jpg'/> </a> <div><a href="/profile/vaibhavsingh100070" title="Pupil vaibhavsingh100070" class="rated-user user-green">vaibhavsingh100070</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 09:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603609" href="?#comment-603609" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603609" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="792197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603609"> <div class="moveup"> <div class="ttypography"><p>Can you please explain for this test case n = 5 a = [ 1, 2, 1, 4, 1] For this output is ** 2**. How in 2 steps we will make this array non decreasing?</p></div> </div> </div> <div class="reply info"> <a class="comment-603609 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603609 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603609"> <li> <div class="comment"> <table class="comment-table" commentId="604681" commentParentId="603609"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604681" href="?#comment-604681" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603609" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604681" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604681" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604681"> <div class="moveup"> <div class="ttypography"><p>Same doubt. Hoping someone to answer.</p><p>Edit: Got it. Should have read the question carefully. It says select any indices not continuous indices.</p><p>for n=5 ans array [ 1 2 1 4 1 ] </p><p>Step 1: Select indices : Select 3 and 5 ( begins from 0) Step 2: Increase by 1 then by 2 ( 2^x-1 , put x=1 and then 2) So array becomes : 1 2 4 4 4 which is non-decreasing.</p></div> </div> </div> <div class="reply info"> <a class="comment-604681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604681"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602409" href="?#comment-602409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602409" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602409"> <div class="moveup"> <div class="ttypography"><p>I have doubt in 1339 B -Sorted Adjacent Differences: If the array is: -2 5 5 6 The answer will be 5 -2 5 6 which is wrong Please explain if i am wrong</p></div> </div> </div> <div class="reply info"> <a class="comment-602409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602409"> <li> <div class="comment"> <table class="comment-table" commentId="602428" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602428" href="?#comment-602428" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602428"> <div class="moveup"> <div class="ttypography"><p>it is wrong because the required condition is not fulfilled as your answer will make seqeunce like this 7&lt;=7&gt;1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602428"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602433" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mestu" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mestu" title="Expert Mestu" class="rated-user user-blue">Mestu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602433" href="?#comment-602433" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602433" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="922247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602433"> <div class="moveup"> <div class="ttypography"><p>For array -2 5 5 6 the answer will be 5 5 -2 6 </p></div> </div> </div> <div class="reply info"> <a class="comment-602433 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602433 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602433"> <li> <div class="comment"> <table class="comment-table" commentId="602473" commentParentId="602433"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602473" href="?#comment-602473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602433" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602473"> <div class="moveup"> <div class="ttypography"><p>yes,but according to tutorial it is printing 5-2 5 6</p></div> </div> </div> <div class="reply info"> <a class="comment-602473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602473"> <li> <div class="comment"> <table class="comment-table" commentId="602740" commentParentId="602473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602740" href="?#comment-602740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602740"> <div class="moveup"> <div class="ttypography"><p>according to tutorial it will print 5 5 -2 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-602740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602740"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602427" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/inazuma_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/inazuma_11" title="Newbie inazuma_11" class="rated-user user-gray">inazuma_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602427" href="?#comment-602427" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602427" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1335781" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602427"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain O(N) approach for div 2C ? I know how to do it in O(NlogN) but not in O(N)</p></div> </div> </div> <div class="reply info"> <a class="comment-602427 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602427 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602427"> <li> <div class="comment"> <table class="comment-table" commentId="602432" commentParentId="602427"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602432" href="?#comment-602432" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602427" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602432" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602432"> <div class="moveup"> <div class="ttypography"><p>While traversing the array keep a count of what maximum difference have you seen so far from the previous element i.e maximum value uptil that i minus the array value at that i. Then once you found the maximum difference than going for finding the position of the highest bit in this maximum difference. The ans is going to be the value of this highest bit + 1. Make sure to include the edge case that if the maximum difference is 0 then the ans is also 0.</p></div> </div> </div> <div class="reply info"> <a class="comment-602432 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602432 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602432"> <li> <div class="comment"> <table class="comment-table" commentId="602492" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602492" href="?#comment-602492" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602492" 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="602492" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602492"> <div class="moveup"> <div class="ttypography"><p>Here is my thinking about this problem, which is much easier to understand: Lets say we need T seconds to make array becoming non descending. On each seconds from 1 to T we can choose any set of numbers from array to add 2^(t-1). It means that for each element of the array, on each second, we have choice to add or not to add this power of 2. So it means we can choose ANY number to add to each of array element. So the question is now simple: what is the min number M so that if for each a[i] we choose some number from 0 up to M to add to it, we can make array non descending. I just go from left to right, if next a[i+1] is less than a[i] I increase it to be equal a[i].</p></div> </div> </div> <div class="reply info"> <a class="comment-602492 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602492 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602492"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602531" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602531" href="?#comment-602531" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602531" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602531"> <div class="moveup"> <div class="ttypography"><p>why do we need to add the 1?</p></div> </div> </div> <div class="reply info"> <a class="comment-602531 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602531 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602531"> <li> <div class="comment"> <table class="comment-table" commentId="602549" commentParentId="602531"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602549" href="?#comment-602549" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602531" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602549" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602549"> <div class="moveup"> <div class="ttypography"><p>because suppose the highest bit is 2 that will be 100 but the time this would have occurred will be 3 seconds(1,2,4). Due to this, we need to add 1 to the highest bit that we obtain.</p></div> </div> </div> <div class="reply info"> <a class="comment-602549 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602549 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602549"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602429" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602429" href="?#comment-602429" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602429" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602429" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602429"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain how the answer of this testcase in problem div2/probC is 3.</p><p>4 2 -1 -3 -4</p></div> </div> </div> <div class="reply info"> <a class="comment-602429 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602429 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602429"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602431" href="?#comment-602431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602431" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602431"> <div class="moveup"> <div class="ttypography"><p>For DIV2D, first root the tree at any leaf (here, leaf = vertex with degree 1), and note that the XOR sum along any root leaf path must be 0. Now, delete all the leaves and the edges that lead from the leaves to their parents. In this graph, to get maximum value of f, assign distinct powers of 2 to each edge. Then re-introduce the leaves and leaf-to-parent edges, and assign them weights such that XOR sum from root to leaf will be zero. Notice that the values assigned to these leaf-to-parent edges will be distinct unless two leaves share the same parents. Thus, the maximum value of f will be n — 1 — (lvs — p), where lvs = number of leaves in this tree and p = number of nodes which have exactly one child leaf.</p><p>To get minimum f, do the same thing above (root tree at any leaf, then delete leaves and all leaf-parent edges). Then, in this new graph, assign weight 2 to the edge incident on the root, and to all other edges assign weight 1. Now, reintroduce the leaves and the leaf-parent edges, and assign these edges weights such that XOR sum along the root leaf path is 0. Notice that you will only have to assign weights of either 2 or 3 to these edges. So f &lt;= 3. The only case left is to work out when f = 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602431"> <li> <div class="comment"> <table class="comment-table" commentId="602644" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zass" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zass" title="Expert zass" class="rated-user user-blue">zass</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602644" href="?#comment-602644" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602644" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="916405" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602644"> <div class="moveup"> <div class="ttypography"><p>In lvs is root considered one of the leaves and in p is the parent of the root considered as one among p when the parent of root only has root as its child?</p></div> </div> </div> <div class="reply info"> <a class="comment-602644 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602644 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602644"> <li> <div class="comment"> <table class="comment-table" commentId="602811" commentParentId="602644"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602811" href="?#comment-602811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602644" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602811" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602811"> <div class="moveup"> <div class="ttypography"><p>In lvs, the root is not considered one of the leaves. And in p, parent of root is not included because root does not have a parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-602811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602811"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602798" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 18:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602798" href="?#comment-602798" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602798" class="CommentVoteFrame" data-commentRating="5" 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;">+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-602798"> <div class="moveup"> <div class="ttypography"><p>Nice explanation but I read your code to understand fully. =)) Code is still the best explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-602798 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602798 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602798"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="650339" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rmaa" style="position: relative;"> <img src='https://userpic.codeforces.org/499170/avatar/6e864314e460334e.jpg'/> </a> <div><a href="/profile/rmaa" title="Expert rmaa" class="rated-user user-blue">rmaa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2020 23:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-650339" href="?#comment-650339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="650339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="499170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-650339"> <div class="moveup"> <div class="ttypography"><p>Thanks so much, your explanation helped me understand this problem 2 months later! :) It's so mind-boggling to understand how one can come up with this construction in time during the contest.</p><p>The reason I want to post here is to add something to your solution in case anyone after me has the same question. (also to just solidify my own understanding) I actually had this question myself while reading — we know that the XOR from the root to all the different leaves must be zero. But how can one prove that the XOR from one leaf to another is also zero? (a path that does not include the root, but rather just two leaves in the tree?) After all we need to make EVERY path between leaves XOR to 0</p><p>The logic is quite simple. As we said before we know XOR of the paths from the root to the two leafs, call them L1 and L2, are both zero. These paths must share some similar segment (specifically its from the LCA(L1, L2) to the root). Call the XOR of this shared segment X. Then we know the XOR from the path from L1 to LCA(L1, L2) = X, and same with the path from L2 to LCA(L1, L2). Because if (x XOR y) = 0, then x = y, and the XOR of the whole path can be broken up the XOR of two segments L1 -&gt; LCA, LCA -&gt; root. (same with L2).</p><p>The editorial also explains this logic a bit but I hope what I wrote can help. </p></div> </div> </div> <div class="reply info"> <a class="comment-650339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-650339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-650339"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602484" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602484" href="?#comment-602484" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602484" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602484" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602484"> <div class="moveup"> <div class="ttypography"><p>I cant understand the editorial of Powered Addition clearly.Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-602484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602484"> <li> <div class="comment"> <table class="comment-table" commentId="602493" commentParentId="602484"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602493" href="?#comment-602493" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602493" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602493"> <div class="moveup"> <div class="ttypography"><p>I just post my 2 cents above, hope it is easier to understand</p></div> </div> </div> <div class="reply info"> <a class="comment-602493 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602493 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602493"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602629" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ZeroNik" style="position: relative;"> <img src='https://userpic.codeforces.org/1336702/avatar/4935627333ab6d15.jpg'/> </a> <div><a href="/profile/ZeroNik" title="Pupil ZeroNik" class="rated-user user-green">ZeroNik</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602629" href="?#comment-602629" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602629" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1336702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602629"> <div class="moveup"> <div class="ttypography"><p>Who can explain problem A again. I don't undersatand why answer is n</p></div> </div> </div> <div class="reply info"> <a class="comment-602629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602629"> <li> <div class="comment"> <table class="comment-table" commentId="602636" commentParentId="602629"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/invincibel31" style="position: relative;"> <img src='https://userpic.codeforces.org/842069/avatar/78296878ae951a3.jpg'/> </a> <div><a href="/profile/invincibel31" title="Expert invincibel31" class="rated-user user-blue">invincibel31</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602636" href="?#comment-602636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602629" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="842069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602636"> <div class="moveup"> <div class="ttypography"><p>ans is equal to n bcz of the vertically standing diamonds in each way there will be only one diamond which would be standing vertically and since the number of diamond in n hence and in n</p></div> </div> </div> <div class="reply info"> <a class="comment-602636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602636"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602791" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hasnaine_" style="position: relative;"> <img src='https://userpic.codeforces.org/553185/avatar/dbae027ec9304551.jpg'/> </a> <div><a href="/profile/Hasnaine_" title="Expert Hasnaine_" class="rated-user user-blue">Hasnaine_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602791" href="?#comment-602791" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602791" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="553185" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602791"> <div class="moveup"> <div class="ttypography"><p><strong>Problem Div1(C), Div2(E):</strong> </p><p>Can anyone please elaborate on why this combination on bitmasking works?</p><p>Or, how to prove this combination works?</p><p>Thanks in advance. </p></div> </div> </div> <div class="reply info"> <a class="comment-602791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602791"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RedSnowstorm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RedSnowstorm" title="Expert RedSnowstorm" class="rated-user user-blue">RedSnowstorm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602796" href="?#comment-602796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602796" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="789793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602796"> <div class="moveup"> <div class="ttypography"><p>Could someone please elaborate a bit more on Div1 C ? I understand the solution up to the first picture, but I don't understand neither the meaning of the second picture nor the rest of the solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602796"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602873" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ateev_mishra7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ateev_mishra7" title="Pupil ateev_mishra7" class="rated-user user-green">ateev_mishra7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602873" href="?#comment-602873" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602873" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174913" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602873"> <div class="moveup"> <div class="ttypography"><p>Why does my solution to Div2-C is not working . <a href="https://codeforces.com/contest/1339/submission/76407068">https://codeforces.com/contest/1339/submission/76407068</a></p><p>can somebody please help me out on this .</p></div> </div> </div> <div class="reply info"> <a class="comment-602873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602873"> <li> <div class="comment"> <table class="comment-table" commentId="603718" commentParentId="602873"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603718" href="?#comment-603718" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603718" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603718" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603718"> <div class="moveup"> <div class="ttypography"><p>Well let's take the sequence as 1 4 1 4, your code outputs 3 while it is supposed to output 2 since you can add 1 and 2 to the third element and get a sorted output.</p></div> </div> </div> <div class="reply info"> <a class="comment-603718 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603718 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603718"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="603291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vyush" style="position: relative;"> <img src='https://userpic.codeforces.org/814106/avatar/d2c40519525d0732.jpg'/> </a> <div><a href="/profile/Vyush" title="Expert Vyush" class="rated-user user-blue">Vyush</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603291" href="?#comment-603291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603291" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603291" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603291"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain division1C/division2E I am not able to understand the approach in the editorial.I got the nim product observation but I don't know how to implement it also i don't get the editorials approach.If anyone could help that would be great.Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-603291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604316" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sheaf" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sheaf" title="Expert sheaf" class="rated-user user-blue">sheaf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 19:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604316" href="?#comment-604316" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604316" 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="604316" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="509827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604316"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, as for Div1E, isn't $$$R=in(P)\cap Q$$$, instead it is $$$R=in(V)\cap Q$$$? The latter just doesn't make sense if you consider the lemma 3. $$$in(V)$$$ is the subset of all vertices that have at least one outgoing edge, $$$in(P)\cap Q$$$ is the subset of all vertices of $$$Q$$$ that have at least one outgoing edge. Then lemma 3, which says there are edges from set $$$S$$$ to $$$R$$$, can't be true because it says that $$$S$$$ — a subset of $$$Q$$$ without outgoing edges — has edges pointing to $$$R$$$. On contrary, if we set $$$R=in(P)\cap Q$$$ we, can prove lemma 3 by forbidding the configuration from the statement. Also, can't really prove part of lemma 4 that says that $$$R$$$ has no cycles without it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604316 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604316 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604316"> <li> <div class="comment"> <table class="comment-table" commentId="604403" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604403" href="?#comment-604403" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604403" 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="604403" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604403"> <div class="moveup"> <div class="ttypography"><p>(erased)</p></div> </div> </div> <div class="reply info"> <a class="comment-604403 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604403 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604403"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604580" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 01:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604580" href="?#comment-604580" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604580" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604580" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604580"> <div class="moveup"> <div class="ttypography"><p>oops, sorry, I understood your comment wrong. To be honest, I don't fully understand approach of this problem, so I would like to call author of this problem directly. <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></p></div> </div> </div> <div class="reply info"> <a class="comment-604580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604580"> <li> <div class="comment"> <table class="comment-table" commentId="604593" commentParentId="604580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604593" href="?#comment-604593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604593" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604593"> <div class="moveup"> <div class="ttypography"><p>Ugh, bad boy. You should be more responsible to your round.</p></div> </div> </div> <div class="reply info"> <a class="comment-604593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604593"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604591" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604591" href="?#comment-604591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604591" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604591"> <div class="moveup"> <div class="ttypography"><p>Oh, I didn't realise that I used the variable $$$V$$$ 2 times. Now I fixed it. When I said $$$in(V) \cap Q$$$ I refered to the $$$V$$$ in Lemma 2. Thanks for pointinh out my mistake.</p></div> </div> </div> <div class="reply info"> <a class="comment-604591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604591"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604631" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 07:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604631" href="?#comment-604631" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604631"> <div class="moveup"> <div class="ttypography"><p>Hi, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, how does observation 1 of edge weight problem work since the shape of tree is determined by input rather than can be arbitrary constructed as in observation 1? Take example input 3 for instance. Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-604631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604631"> <li> <div class="comment"> <table class="comment-table" commentId="604757" commentParentId="604631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604757" href="?#comment-604757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604757" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604757"> <div class="moveup"> <div class="ttypography"><p><img alt="ex1" src="/predownloaded/a2/a8/a2a877e5c47802fc77cb6bee8965a15f80b6e799.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You can see that we can make $$$f = 1$$$ in this tree anyway.</p></div> </div> </div> <div class="reply info"> <a class="comment-604757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604757"> <li> <div class="comment"> <table class="comment-table" commentId="605625" commentParentId="604757"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605625" href="?#comment-605625" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604757" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605625" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605625"> <div class="moveup"> <div class="ttypography"><p>I must misunderstand your meaning, but doesn't f=2 in the graph since there are weight of 1 and 2?</p><p>Or do you mean that the edge on 7-4-3 could be equivalent to a single edge with weight of 3=weight(7,4) xor weight(4,3)=2 xor 1? Thus in this way the observation 1 can be applied?</p></div> </div> </div> <div class="reply info"> <a class="comment-605625 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605625 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605625"> <li> <div class="comment"> <table class="comment-table" commentId="605631" commentParentId="605625"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605631" href="?#comment-605631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605625" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605631"> <div class="moveup"> <div class="ttypography"><p>This picture shows how you can manage $$$f \le 3$$$ in this tree with first observation. By &quot; <em>You can see that we can make $$$f = 1$$$ in this tree any</em> &quot; I mean you can replace all weights $$$2$$$ to $$$1$$$ to make $$$f = 1$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-605631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605631"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/karanbhatia116" style="position: relative;"> <img src='https://userpic.codeforces.org/872128/avatar/afb324a25af3a491.jpg'/> </a> <div><a href="/profile/karanbhatia116" title="Newbie karanbhatia116" class="rated-user user-gray">karanbhatia116</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604739" href="?#comment-604739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872128" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604739"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain me the second test case for Div1A/Div2C(<a href="/contest/1338/problem/A" title="Codeforces Round 633 (Div. 1)">1338A - Powered Addition</a>)?</p> <pre><code>Input: 6 3 1000000000 0 -1000000000 1 6 2 -1000000000 1000000000 2 1000000000 -1000000000 2 1000000000 1000000000 2 -1000000000 -1000000000 Output: 31 0 0 31 0 0 </code></pre><p>How is the output 31 and not 32? If it is 31 then we must have added 2^30 in 0 and -1000000000 but that does not make the array non-decreasing in the first test case.</p></div> </div> </div> <div class="reply info"> <a class="comment-604739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604739"> <li> <div class="comment"> <table class="comment-table" commentId="604760" commentParentId="604739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 12:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604760" href="?#comment-604760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604760" 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="604760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604760"> <div class="moveup"> <div class="ttypography"><p>Select $$$2$$$-nd index at last second only, and $$$3$$$-rd index all the time. Then you get </p><p>$$$a = [10^{9}, 0, -10^{9}] \to [10^{9}, 0 + 2^{30}, -10^{9} + 2^{0} + 2^{1} + \ldots + 2^{30}] = [1000000000, 1073741824, 1147483647]$$$</p><p>So you can make $$$a$$$ non-decreasing in $$$31$$$ seconds.</p></div> </div> </div> <div class="reply info"> <a class="comment-604760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604760"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605553" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 09:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605553" href="?#comment-605553" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605553" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605553"> <div class="moveup"> <div class="ttypography"><p>why does the answer for div2-C depends only on largest difference? Can someone explain in detailed manner i am unable to get the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-605553 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605553 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605553"> <li> <div class="comment"> <table class="comment-table" commentId="605637" commentParentId="605553"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605637" href="?#comment-605637" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605553" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605637" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605637" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605637"> <div class="moveup"> <div class="ttypography"><p>Fact 1: $$$2^{0} + 2^{1} + \ldots + 2^{t-1} \lt 2^{t}$$$.</p><p>This means if you want to add something equal or bigger than $$$2^{t}$$$ on some position, then you should use more than $$$t$$$ seconds.</p><p>Fact 2: Required seconds is determined by maximum bit of difference.</p><p>From two facts you can observe that smaller difference leads to shorter time.</p><p>I will write few examples below;</p> <ul> <li>diff = 0 -&gt; 0 second</li> <li>diff = 1 -&gt; 1 second ($$$1 = 2^{0}$$$)</li> <li>diff = 2 -&gt; 2 seconds ($$$2 = 2^{1}$$$)</li> <li>diff = 3 -&gt; 2 seconds ($$$3 = 2^{0} + 2^{1}$$$)</li> <li>diff = 4 -&gt; 3 seconds ($$$4 = 2^{2}$$$)</li> <li>diff = 5 -&gt; 3 seconds ($$$5 = 2^{0} + 2^{2}$$$)</li> <li>diff = 6 -&gt; 3 seconds ($$$6 = 2^{1} + 2^{2}$$$)</li> <li>diff = 7 -&gt; 3 seconds ($$$7 = 2^{0} + 2^{1} + 2^{2}$$$)</li> <li>...</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-605637 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605637 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605637"> <li> <div class="comment"> <table class="comment-table" commentId="605676" commentParentId="605637"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 12:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605676" href="?#comment-605676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605637" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605676"> <div class="moveup"> <div class="ttypography"><p>Thank you for your explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-605676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605676"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605607" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anshul23" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anshul23" title="Expert anshul23" class="rated-user user-blue">anshul23</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 10:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605607" href="?#comment-605607" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605607" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="551535" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-605607"> <div class="moveup"> <div class="ttypography"><p>Nice editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-605607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605607"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grapo_Oranges" style="position: relative;"> <img src='https://userpic.codeforces.org/1443313/avatar/3242fe30f43d5e9f.jpg'/> </a> <div><a href="/profile/grapo_Oranges" title="Expert grapo_Oranges" class="rated-user user-blue">grapo_Oranges</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 13:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605691" href="?#comment-605691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605691" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605691"> <div class="moveup"> <div class="ttypography"><p>@Anyone who solved Div2. D during the contest, can you explain how did you actually figure out the solution and was there any specific problem you ever did in past that helped you to solve this problem?</p></div> </div> </div> <div class="reply info"> <a class="comment-605691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606212" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ankit_12" style="position: relative;"> <img src='https://userpic.codeforces.org/1461518/avatar/2c0c3df83d1920d2.jpg'/> </a> <div><a href="/profile/Ankit_12" title="Pupil Ankit_12" class="rated-user user-green">Ankit_12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 10:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606212" href="?#comment-606212" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="606212" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="606212" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1461518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606212"> <div class="moveup"> <div class="ttypography"><p>Why this sequence is not correct for n=9, A/C to question Perfect Triples please Any one Help???</p><p>9 : 1 2 3 4 3 7 8 4 12</p></div> </div> </div> <div class="reply info"> <a class="comment-606212 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606212 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606212"> <li> <div class="comment"> <table class="comment-table" commentId="606260" commentParentId="606212"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 13:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606260" href="?#comment-606260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606212" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606260"> <div class="moveup"> <div class="ttypography"><p>Because $$$3$$$ is used twice in your sequence.</p></div> </div> </div> <div class="reply info"> <a class="comment-606260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606260"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606777" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/striver_79" style="position: relative;"> <img src='https://userpic.codeforces.org/584222/avatar/92d0d608686eabcc.jpg'/> </a> <div><a href="/profile/striver_79" title="Candidate Master striver_79" class="rated-user user-violet">striver_79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 13:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606777" href="?#comment-606777" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606777" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="584222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606777"> <div class="moveup"> <div class="ttypography"><p>Video editorial for <a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div2D</a>/<a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div1B</a>: </p></div> </div> </div> <div class="reply info"> <a class="comment-606777 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606777 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606777"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607351" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/richikchanda1999" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/richikchanda1999" title="Pupil richikchanda1999" class="rated-user user-green">richikchanda1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 18:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607351" href="?#comment-607351" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607351" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="510979" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607351"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces,</p><p>Can anyone help me to come up with a better approach to the excluded problem (<a href="https://codeforces.com/gym/276159/problem/D1A_old">https://codeforces.com/gym/276159/problem/D1A_old</a>) apart from the brute-force approach which is giving TLE?</p></div> </div> </div> <div class="reply info"> <a class="comment-607351 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607351 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607351"> <li> <div class="comment"> <table class="comment-table" commentId="608851" commentParentId="607351"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/22/2020 18:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-608851" href="?#comment-608851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607351" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="608851" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="608851" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-608851"> <div class="moveup"> <div class="ttypography"><p>$$$x \oplus (x \cdot 2^{30}) = x \cdot (1 + 2^{30})$$$ if $$$x &lt; 2^{30}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-608851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-608851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-608851"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="619618" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/10/2020 21:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-619618" href="?#comment-619618" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="619618" 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="619618" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-619618"> <div class="moveup"> <div class="ttypography"><p>After a few weeks when I want to solve the problems I just realized the Editorial is so beautiful, those well-illustrated pictures and interesting stories made the Editorial so great!</p><p>But I had problems solving D1E. I cannot figure out why the <strong>Lemma 3</strong> and <strong>Lemma 6a/b</strong> are correct (And of course the final observations). Can you give proofs for them?</p><p><strong>UPD: After asking others, now I understood. Anyway, thanks the great Editorial!</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-619618 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-619618 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-619618"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="620074" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/11/2020 17:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620074" href="?#comment-620074" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="620074" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620074"> <div class="moveup"> <div class="ttypography"><p>i found a crazy solution of div1B <a href="https://codeforces.com/contest/1338/submission/76346806">https://codeforces.com/contest/1338/submission/76346806</a> can anyone plz explain the logic</p></div> </div> </div> <div class="reply info"> <a class="comment-620074 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620074 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620074"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="630800" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shpvb" style="position: relative;"> <img src='https://userpic.codeforces.org/720608/avatar/3fa49fe2fc134d7b.jpg'/> </a> <div><a href="/profile/shpvb" title="Candidate Master shpvb" class="rated-user user-violet">shpvb</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/27/2020 13:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-630800" href="?#comment-630800" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="630800" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-630800"> <div class="moveup"> <div class="ttypography"><p>Can someone provide insight into the mathematical induction referred to in observation 2 of div1C (Perfect Triples)?</p></div> </div> </div> <div class="reply info"> <a class="comment-630800 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-630800 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-630800"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="792521" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Livu_sz" style="position: relative;"> <img src='https://userpic.codeforces.org/1922428/avatar/3153d345afda896c.jpg'/> </a> <div><a href="/profile/Livu_sz" title="Expert Livu_sz" class="rated-user user-blue">Livu_sz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/19/2021 06:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-792521" href="?#comment-792521" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="792521" 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="792521" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1922428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-792521"> <div class="moveup"> <div class="ttypography"><p>B was tough</p></div> </div> </div> <div class="reply info"> <a class="comment-792521 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-792521 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-792521"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1064206" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sartq" style="position: relative;"> <img src='https://userpic.codeforces.org/3093050/avatar/ec7dcd19bb83efab.jpg'/> </a> <div><a href="/profile/sartq" title="Newbie sartq" class="rated-user user-gray">sartq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2023 06:30">5 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1064206" href="?#comment-1064206" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1064206" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="3093050" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1064206"> <div class="moveup"> <div class="ttypography"><p>In div2B can we solve the problem using a hashMap, like storing the values of differences of array and their indexes?</p></div> </div> </div> <div class="reply info"> <a class="comment-1064206 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1064206 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1064206"> </ul> </div> <br/> <div id="editBox-82006" 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 firstPreview82006 = true; var lastPreviewContent82006 = ''; 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=82006] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=82006] 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-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, 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:28:37</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:'81288c53eb1e161c',t:'MTY5NjcwNjkxNy4zNTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1338B
1338
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$$$ вершинах. Вы должны назначить <span class="tex-font-style-bf">положительный</span> вес каждому ребру, чтобы выполнялось следующее условие:</p><ul> <li> Для каждых двух разных листов $$$v_{1}$$$ и $$$v_{2}$$$ этого дерева, <a href="https://ru.wikipedia.org/wiki/Битовая_операция#Исключающее_ИЛИ">побитовое исключающее ИЛИ</a> весов всех ребер на простом пути между $$$v_{1}$$$ и $$$v_{2}$$$ должно быть равно $$$0$$$. </li></ul><p>Обратите внимание, что вы можете назначать <span class="tex-font-style-bf">очень большие</span> натуральные числа (такие как $$$10^{(10^{10})}$$$).</p><p>Гарантируется, что такое назначение всегда существует при данных ограничениях. Теперь определим $$$f$$$ как <span class="tex-font-style-bf">количество различных весов</span> среди назначенных весов.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/822324016e7a6837336849481ecbe0190b03dfa3.png" style="max-width: 100.0%;max-height: 100.0%;"/> В этом примере назначение верно, потому что побитовое исключающее ИЛИ всех весов ребер между каждой парой листьев равно $$$0$$$. Значение $$$f$$$ здесь равно $$$2$$$, потому что есть $$$2$$$ различных веса ребер ($$$4$$$ и $$$5$$$).<p><img class="tex-graphics" src="https://espresso.codeforces.com/82d52d5070be134d11729e65fab0a8709aae6b3f.png" style="max-width: 100.0%;max-height: 100.0%;"/> В этом примере назначение не удовлетворяет условию, поскольку побитовое исключающее ИЛИ всех весов ребер между вершинами $$$1$$$ и $$$6$$$ ($$$3, 4, 5, 4$$$) не равно $$$0$$$. </p></center><p>Чему равны минимальное и максимальное возможные значения $$$f$$$ для данного дерева? Найдите и выведите оба.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$3 \le n \le 10^{5}$$$)  — количество вершин в данном дереве.</p><p>$$$i$$$-я из следующих $$$n-1$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$)  — это означает, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Гарантируется, что данный граф образует дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа  — минимальное и максимальное возможное значения $$$f$$$, которые могут быть получены из правильного назначения данного дерева. Обратите внимание, что такое назначение всегда существует при данных ограничениях.</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 3 2 3 3 4 4 5 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 3 2 3 3 4 4 5 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 2 2 7 3 4 4 7 5 6 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере возможные назначения для минимума и максимума показаны на рисунке ниже. Конечно, есть и другие назначения. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e7bf97f0144ccdc05c3ef43ccaa89a3d0c9ce1dc.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором примере возможные назначения для минимума и максимума показаны на рисунке ниже. Значение $$$f$$$ для правильного назначения этого дерева всегда равно $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f98bbf02e8b21aed9fd5a82be44c2dcd71808c3c.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В третьем примере возможные назначения для минимума и максимума показаны на рисунке ниже. Конечно, есть и другие назначения. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0a99edbccedea10ea506d2c7bd3d027a4bdf17ce.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="d211d970024c4c46c6572ca13b49bc32"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="5c85cbb657e064c2cfa3c38de5074b5925e3ec82"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d211d970024c4c46c6572ca13b49bc32'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1338%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='d211d970024c4c46c6572ca13b49bc32'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1338">Codeforces Round 633 (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='d211d970024c4c46c6572ca13b49bc32'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1338/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='d211d970024c4c46c6572ca13b49bc32'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590532"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d211d970024c4c46c6572ca13b49bc32'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590532"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10753" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10760" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1338">Задачи</a></li> <li><a href="/contest/1338/submit">Отослать</a></li> <li><a href="/contest/1338/my">Мои посылки</a></li> <li><a href="/contest/1338/status">Статус</a></li> <li><a href="/contest/1338/hacks">Взломы</a></li> <li><a href="/contest/1338/room/1">Комната</a></li> <li><a href="/contest/1338/standings">Положение</a></li> <li><a href="/contest/1338/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c2e4434824f85457a37161e0bf03a456bb145214"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ вершинах. Вы должны назначить <span class="tex-font-style-bf">положительный</span> вес каждому ребру, чтобы выполнялось следующее условие:</p><ul> <li> Для каждых двух разных листов $$$v_{1}$$$ и $$$v_{2}$$$ этого дерева, <a href="https://ru.wikipedia.org/wiki/Битовая_операция#Исключающее_ИЛИ">побитовое исключающее ИЛИ</a> весов всех ребер на простом пути между $$$v_{1}$$$ и $$$v_{2}$$$ должно быть равно $$$0$$$. </li></ul><p>Обратите внимание, что вы можете назначать <span class="tex-font-style-bf">очень большие</span> натуральные числа (такие как $$$10^{(10^{10})}$$$).</p><p>Гарантируется, что такое назначение всегда существует при данных ограничениях. Теперь определим $$$f$$$ как <span class="tex-font-style-bf">количество различных весов</span> среди назначенных весов.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/822324016e7a6837336849481ecbe0190b03dfa3.png" style="max-width: 100.0%;max-height: 100.0%;" /> В этом примере назначение верно, потому что побитовое исключающее ИЛИ всех весов ребер между каждой парой листьев равно $$$0$$$. Значение $$$f$$$ здесь равно $$$2$$$, потому что есть $$$2$$$ различных веса ребер ($$$4$$$ и $$$5$$$).<p><img class="tex-graphics" src="https://espresso.codeforces.com/82d52d5070be134d11729e65fab0a8709aae6b3f.png" style="max-width: 100.0%;max-height: 100.0%;" /> В этом примере назначение не удовлетворяет условию, поскольку побитовое исключающее ИЛИ всех весов ребер между вершинами $$$1$$$ и $$$6$$$ ($$$3, 4, 5, 4$$$) не равно $$$0$$$. </p></center><p>Чему равны минимальное и максимальное возможные значения $$$f$$$ для данного дерева? Найдите и выведите оба.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$3 \le n \le 10^{5}$$$)  — количество вершин в данном дереве.</p><p>$$$i$$$-я из следующих $$$n-1$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$)  — это означает, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Гарантируется, что данный граф образует дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа  — минимальное и максимальное возможное значения $$$f$$$, которые могут быть получены из правильного назначения данного дерева. Обратите внимание, что такое назначение всегда существует при данных ограничениях.</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 3 2 3 3 4 4 5 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 3 2 3 3 4 4 5 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 2 2 7 3 4 4 7 5 6 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере возможные назначения для минимума и максимума показаны на рисунке ниже. Конечно, есть и другие назначения. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e7bf97f0144ccdc05c3ef43ccaa89a3d0c9ce1dc.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере возможные назначения для минимума и максимума показаны на рисунке ниже. Значение $$$f$$$ для правильного назначения этого дерева всегда равно $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f98bbf02e8b21aed9fd5a82be44c2dcd71808c3c.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В третьем примере возможные назначения для минимума и максимума показаны на рисунке ниже. Конечно, есть и другие назначения. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0a99edbccedea10ea506d2c7bd3d027a4bdf17ce.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/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:35</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249df278713a71',t:'MTY5NjY2NTY5NS40MTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*1800"]
https://codeforces.com/blog/entry/75913
<!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="8bc765f3680682fd8f2decef62cad97d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Codeforces Round #633 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #633 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='8bc765f3680682fd8f2decef62cad97d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F75913">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='8bc765f3680682fd8f2decef62cad97d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:36:25</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:36:25</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='8bc765f3680682fd8f2decef62cad97d'/> <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/McDic">McDic</a></li> <li class="current selectedLava"><a href="/blog/McDic">Blog</a></li> <li><a href="/teams/with/McDic">Teams</a></li> <li><a href="/submissions/McDic">Submissions</a></li> <li><a href="/groups/with/McDic">Groups</a></li> <li><a href="/contests/with/McDic">Contests</a></li> <li><a href="/contests/writer/McDic">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/McDic" style="text-decoration:none;color:black !important;">McDic's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="76444"> <div class="title"> <a href="/blog/entry/75913"> <p>Codeforces Round #633 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a>, <a href="/topic/76444/en2">history</a>, <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p>Hello! I hope all of you enjoyed my contest!</p> <div class="problemTutorial" problemcode="1339A">Tutorial is loading...</div><p><strong>Behind story of A</strong>:</p> <ul> <li>I tried to make the easiest Div2A ever. Will it work? :)</li> </ul> <div class="problemTutorial" problemcode="1339B">Tutorial is loading...</div><p><strong>Behind story of B</strong>:</p> <ul> <li>I tried to block various heuristics. There were some critical heuristics which could pass so many cases. Fortunately I blocked them during testing period, so I hope there won't be much FST this time.</li> </ul> <div class="problemTutorial" problemcode="1338A">Tutorial is loading...</div><p><strong>Behind story of D2C/D1A</strong>:</p> <ul> <li>Originally, there was a different problem for this position. But it used XOR. As I made new D2E/D1C problem, I threw old D2C/D1A away and put this.</li> </ul> <div class="problemTutorial" problemcode="1338B">Tutorial is loading...</div><p><strong>Behind story of D2D/D1B</strong>:</p> <ul> <li>This problem is the most popular problem among testers. I also like this problem a lot.</li> </ul> <div class="problemTutorial" problemcode="1338C">Tutorial is loading...</div><p><strong>Behind story of D2E/D1C</strong>:</p> <ul> <li>Feedback for this problem was too different by testers.</li> <li>I made this problem by modifying <a href="https://codeforces.com/contest/1242/problem/D">Number Discovery</a>, which is one of my previous problems.</li> <li>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this.</li> </ul> <div class="problemTutorial" problemcode="1338D">Tutorial is loading...</div><p><strong>Behind story of D1D</strong>:</p> <ul> <li>This problem was supposed to be D2E at first. But all LGM testers failed this problem during VC, so we thought that this problem's difficulty is high. Meanwhile, I found that old D1D problem can be easily googled, so we removed that problem, push this problem to be D1D, and made another D1C problem. I will share old D1D later.</li> </ul> <div class="problemTutorial" problemcode="1338E">Tutorial is loading...</div><p><strong>Behind story of D1E</strong>:</p> <ul> <li>Thanks <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a> for writing this problem. She is genius in both singing and problemsolving.</li> </ul></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/1338" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 1)</a> </span> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1339" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-88959-76444").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "88959", blogEntryId: "75913", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=mcdic" class="tag notice" style="text-decoration: none;">mcdic</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-76444"><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'>+346</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-76444"><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/McDic"><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/McDic"> McDic </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/75913#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/75913#comments"> 225 </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="82006"> <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 (171)</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="601867" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stefdasca" style="position: relative;"> <img src='https://userpic.codeforces.org/492453/avatar/429fc64e07ff3f4.jpg'/> </a> <div><a href="/profile/stefdasca" title="Candidate Master stefdasca" class="rated-user user-violet">stefdasca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601867" href="?#comment-601867" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601867" 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="601867" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="492453" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601867"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=crOSe84Q6HQ">Video tutorial for div1A/div2C</a></p><p><a href="https://www.youtube.com/watch?v=MMtnJDMM3IE">Video tutorial for div1B/div2D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-601867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601867"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601870" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kerO_o" style="position: relative;"> <img src='https://userpic.codeforces.org/406813/avatar/a505f416e75a37bd.jpg'/> </a> <div><a href="/profile/kerO_o" title="Master kerO_o" class="rated-user user-orange">kerO_o</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601870" href="?#comment-601870" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601870" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="406813" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601870"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-601870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601870"> <li> <div class="comment"> <table class="comment-table" commentId="601963" commentParentId="601870"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601963" href="?#comment-601963" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601963" class="CommentVoteFrame" data-commentRating="30" 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:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601963"> <div class="moveup"> <div class="ttypography"><p>what does this &quot;orz&quot; mean? </p></div> </div> </div> <div class="reply info"> <a class="comment-601963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601963"> <li> <div class="comment"> <table class="comment-table" commentId="602114" commentParentId="601963"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yash18" style="position: relative;"> <img src='https://userpic.codeforces.org/858176/avatar/3cdce86e6de339b8.jpg'/> </a> <div><a href="/profile/yash18" title="Pupil yash18" class="rated-user user-green">yash18</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602114" href="?#comment-602114" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602114" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602114" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="858176" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602114"> <div class="moveup"> <div class="ttypography"><p>Bow down! Bow down to the <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602114 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602114 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602114"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601879" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SkySurfer" style="position: relative;"> <img src='https://userpic.codeforces.org/684272/avatar/41e617735365cc0e.jpg'/> </a> <div><a href="/profile/SkySurfer" title="Specialist SkySurfer" class="rated-user user-cyan">SkySurfer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601879" href="?#comment-601879" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601879" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="684272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601879"> <div class="moveup"> <div class="ttypography"><p>Best Editorial Ever ....Nice Explanation Of both Problems and Solutions . </p></div> </div> </div> <div class="reply info"> <a class="comment-601879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601879"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601890" href="?#comment-601890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601890" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601890" class="CommentVoteFrame" data-commentRating="32" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+32</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601890"> <div class="moveup"> <div class="ttypography"><p>For Div1C, I found out that the nth tuple (an, bn, cn) is basically this: (found via OEIS)</p> <ol> <li><p>an -&gt; nth number with odd number of bits</p></li> <li><p>bn -&gt; nim_multiplcation(2, an) (<a href="https://oeis.org/A006015">https://oeis.org/A006015</a>)</p></li> <li><p>cn = an ^ bn.</p></li> </ol><p>But I was still not able to solve the problem because I didn't know nim multiplication nor did I find any implementation over the net.</p></div> </div> </div> <div class="reply info"> <a class="comment-601890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601890"> <li> <div class="comment"> <table class="comment-table" commentId="601914" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601914" href="?#comment-601914" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601914" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601914"> <div class="moveup"> <div class="ttypography"><p>Nim Arithmetic is definitely overkill for this problem. </p></div> </div> </div> <div class="reply info"> <a class="comment-601914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601914"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="601919" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601919" href="?#comment-601919" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601919" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601919" class="CommentVoteFrame" data-commentRating="71" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+71</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601919"> <div class="moveup"> <div class="ttypography"><p>We found that during testing and thought it wasn't much of an issue exactly because of that, probably you'd spend more time searching about nim multiplication than if you just solved the problem lol</p></div> </div> </div> <div class="reply info"> <a class="comment-601919 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601919 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601919"> <li> <div class="comment"> <table class="comment-table" commentId="601942" commentParentId="601919"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601942" href="?#comment-601942" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601919" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601942" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601942"> <div class="moveup"> <div class="ttypography"><p>Yeah, that is what happened ... I kept on searching for nim multiplcation here and there and wasted too much time. I should have come up with some other approaches ... </p></div> </div> </div> <div class="reply info"> <a class="comment-601942 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601942 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601942"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602731" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602731" href="?#comment-602731" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602731" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602731"> <div class="moveup"> <div class="ttypography"><p>A solution with nim multiplcation: <a href="/contest/1338/submission/76499145" title="Submission 76499145 by amane-ame">76499145</a></p><p>There is no doubt that it is much more complicated than the general solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602731 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602731 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602731"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601893" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Endagorion" style="position: relative;"> <img src='https://userpic.codeforces.org/1643/avatar/5c0b493cf8428ab6.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Endagorion" title="International Grandmaster Endagorion" class="rated-user user-red">Endagorion</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601893" href="?#comment-601893" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601893" class="CommentVoteFrame" data-commentRating="192" data-commentUserId="1643" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+192</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601893"> <div class="moveup"> <div class="ttypography"><p>I don't have proof, but in div1C any triple appears to be $$$(x, x \otimes 2, x \otimes 3)$$$, where $$$\otimes$$$ is nim multiplication.</p></div> </div> </div> <div class="reply info"> <a class="comment-601893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601893"> <li> <div class="comment"> <table class="comment-table" commentId="601983" commentParentId="601893"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601983" href="?#comment-601983" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601983" class="CommentVoteFrame" data-commentRating="64" 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;">+64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601983"> <div class="moveup"> <div class="ttypography"><p>:o</p></div> </div> </div> <div class="reply info"> <a class="comment-601983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601983"> <li> <div class="comment"> <table class="comment-table" commentId="602418" commentParentId="601983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jerry__Jiang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jerry__Jiang" title="Master Jerry__Jiang" class="rated-user user-orange">Jerry__Jiang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602418" href="?#comment-602418" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601983" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602418" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1198521" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602418"> <div class="moveup"> <div class="ttypography"><p>:)</p></div> </div> </div> <div class="reply info"> <a class="comment-602418 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602418 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602418"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601939" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601939" href="?#comment-601939" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601939" 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="601939" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-41" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601939"> <div class="moveup"> <div class="ttypography"><p>[DELETED]</p></div> </div> </div> <div class="reply info"> <a class="comment-601939 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601939 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601939"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prodelta" style="position: relative;"> <img src='https://userpic.codeforces.org/847522/avatar/e144f36263828062.jpg'/> </a> <div><a href="/profile/prodelta" title="Pupil prodelta" class="rated-user user-green">prodelta</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601950" href="?#comment-601950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601950" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="847522" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601950"> <div class="moveup"> <div class="ttypography"><p>System testing is finished , Editorials are out , but my submission for Problem — A still shows Pretests Passed . Link : <a href="https://codeforces.com/contest/1339/submission/76340409">Here</a></p><p>Have I committed some fatal sin for which I am being given such a brutal punishment ?</p><p>What should I do now ?</p></div> </div> </div> <div class="reply info"> <a class="comment-601950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601950"> <li> <div class="comment"> <table class="comment-table" commentId="601964" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shubhammitt" style="position: relative;"> <img src='https://userpic.codeforces.org/785906/avatar/ecb76ca8bc2663f4.jpg'/> </a> <div><a href="/profile/shubhammitt" title="Expert shubhammitt" class="rated-user user-blue">shubhammitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601964" href="?#comment-601964" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601964" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="785906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601964"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-601964 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601964 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601964"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602003" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602003" href="?#comment-602003" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602003" 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-602003"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-602003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602003"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602451" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chidoring" style="position: relative;"> <img src='https://userpic.codeforces.org/1455809/avatar/d62042cde12a7b4e.jpg'/> </a> <div><a href="/profile/chidoring" title="Pupil chidoring" class="rated-user user-green">chidoring</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602451" href="?#comment-602451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602451" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1455809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602451"> <div class="moveup"> <div class="ttypography"><p>rip</p></div> </div> </div> <div class="reply info"> <a class="comment-602451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602451"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601953" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_DynamicCube" style="position: relative;"> <img src='https://userpic.codeforces.org/1381092/avatar/ca9726e93700302b.jpg'/> </a> <div><a href="/profile/_DynamicCube" title="Pupil _DynamicCube" class="rated-user user-green">_DynamicCube</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601953" href="?#comment-601953" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601953" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1381092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601953"> <div class="moveup"> <div class="ttypography"><p>재밌는 문제들 감사합니다! (Thank you for the interesting questions!)</p></div> </div> </div> <div class="reply info"> <a class="comment-601953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601953"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601956" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AceKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AceKing" title="Candidate Master AceKing" class="rated-user user-violet">AceKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601956" href="?#comment-601956" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601956" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="910788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601956"> <div class="moveup"> <div class="ttypography"><p>Fastest editorial I have ever seen!</p></div> </div> </div> <div class="reply info"> <a class="comment-601956 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601956 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601956"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601960" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601960" href="?#comment-601960" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601960" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601960" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601960"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces, I don't have any idea how to approach problems like Div2.D/Div1.B, can someone give me an advice? I am not sure what should I learn first in order to be able to come with a solution to this problem. Thanks :)</p></div> </div> </div> <div class="reply info"> <a class="comment-601960 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601960 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601960"> <li> <div class="comment"> <table class="comment-table" commentId="602364" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 06:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602364" href="?#comment-602364" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602364" class="CommentVoteFrame" data-commentRating="3" 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: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-602364"> <div class="moveup"> <div class="ttypography"><p>From my experience, Div 2 D tends to vary quite bit. I think the best way to go about it is to just keep on practicing a bunch of div 2 D, and look at editorials if you don't quite understand. Also, nice profile picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602364"> <li> <div class="comment"> <table class="comment-table" commentId="602461" commentParentId="602364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602461" href="?#comment-602461" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602364" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602461" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602461" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602461"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, I will keep practicing then :D. PS: I also like your picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602461 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602461 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602461"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602499" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602499" href="?#comment-602499" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602499" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602499"> <div class="moveup"> <div class="ttypography"><p>Well from my experience, it appears atleast one of C/D almost always involves graphs and/or DP. I'd recommend first learning all about graphs, especially some important techniques like DFS, BFS, multi-source BFS, SCC, bridges, cut-vertices etc.[Graphs are really awesome :] Then later move on to DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-602499 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602499 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602499"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604120" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 16:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604120" href="?#comment-604120" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604120" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604120"> <div class="moveup"> <div class="ttypography"><p>IMO you should first learn a little advanced algorithms and data structures and etc., also solve-up contests and past ones, i say the best way is to take virtual contests and then solve the rest of the problems excluding the cases you full the contest :). Also solve Div2.E after the contests, it's fine if you cant solve them, just take your time and try your best then go to editorial and make sure you fully understand the editorial and the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604120"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601962" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601962" href="?#comment-601962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601962" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-118" 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;">-118</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601962"> <div class="moveup"> <div class="ttypography"><p>i think it is better to provide codes instead of stories</p></div> </div> </div> <div class="reply info"> <a class="comment-601962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601962"> <li> <div class="comment"> <table class="comment-table" commentId="601995" commentParentId="601962"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601995" href="?#comment-601995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601995" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601995"> <div class="moveup"> <div class="ttypography"><p>That's why the button showing number of solves next to a problem exists. Click on that and you can see many codes and sort by speed, code length, etc.</p></div> </div> </div> <div class="reply info"> <a class="comment-601995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601995"> <li> <div class="comment"> <table class="comment-table" commentId="601999" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601999" href="?#comment-601999" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601999" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-30" 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;">-30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601999"> <div class="moveup"> <div class="ttypography"><p>I know that, But I want to see the code of the explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-601999 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601999 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601999"> <li> <div class="comment"> <table class="comment-table" commentId="602002" commentParentId="601999"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602002" href="?#comment-602002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601999" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602002" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602002"> <div class="moveup"> <div class="ttypography"><p>Wtf does that mean. Every code is most likely some variation of the explanation if it passed...</p></div> </div> </div> <div class="reply info"> <a class="comment-602002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602002"> <li> <div class="comment"> <table class="comment-table" commentId="602006" commentParentId="602002"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602006" href="?#comment-602006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602002" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602006" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-55" 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;">-55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602006"> <div class="moveup"> <div class="ttypography"><p>No</p></div> </div> </div> <div class="reply info"> <a class="comment-602006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602006"> <li> <div class="comment"> <table class="comment-table" commentId="602113" commentParentId="602006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602113" href="?#comment-602113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602113" class="CommentVoteFrame" data-commentRating="20" 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: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-602113"> <div class="moveup"> <div class="ttypography"><p>Yes</p></div> </div> </div> <div class="reply info"> <a class="comment-602113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602113"> <li> <div class="comment"> <table class="comment-table" commentId="602122" commentParentId="602113"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602122" href="?#comment-602122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602113" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602122" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" 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;">-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-602122"> <div class="moveup"> <div class="ttypography"><p>No is no</p></div> </div> </div> <div class="reply info"> <a class="comment-602122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602122"> <li> <div class="comment"> <table class="comment-table" commentId="602331" commentParentId="602122"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602331" href="?#comment-602331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602331" class="CommentVoteFrame" data-commentRating="41" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602331"> <div class="moveup"> <div class="ttypography"><p>Dumb is dumb</p></div> </div> </div> <div class="reply info"> <a class="comment-602331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602331"> <li> <div class="comment"> <table class="comment-table" commentId="602624" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 15:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602624" href="?#comment-602624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602624" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" 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;">-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-602624"> <div class="moveup"> <div class="ttypography"><p>Who is dumb there?</p></div> </div> </div> <div class="reply info"> <a class="comment-602624 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602624 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602624"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604121" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:02">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604121" href="?#comment-604121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604121" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604121"> <div class="moveup"> <div class="ttypography"><p>BABA IS YOU</p></div> </div> </div> <div class="reply info"> <a class="comment-604121 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604121 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604121"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604142" commentParentId="604121"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604142" href="?#comment-604142" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604142" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604142"> <div class="moveup"> <div class="ttypography"><p>Who is BABA?</p></div> </div> </div> <div class="reply info"> <a class="comment-604142 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604142 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604142"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604648" commentParentId="604142"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Suleyman.A" style="position: relative;"> <img src='https://userpic.codeforces.org/82791/avatar/fc8479c7406b79a3.jpg'/> </a> <div><a href="/profile/Suleyman.A" title="Expert Suleyman.A" class="rated-user user-blue">Suleyman.A</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604648" href="?#comment-604648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604142" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604648" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="82791" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604648"> <div class="moveup"> <div class="ttypography"><p>He is husband of your mother</p></div> </div> </div> <div class="reply info"> <a class="comment-604648 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604648 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604648"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602019" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602019" href="?#comment-602019" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602019" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602019"> <div class="moveup"> <div class="ttypography"><p>Its always better if editorial provides code or snippet about their approach</p></div> </div> </div> <div class="reply info"> <a class="comment-602019 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602019 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602019"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rajiv_kale" style="position: relative;"> <img src='https://userpic.codeforces.org/758545/avatar/575c69bbc5b5a715.jpg'/> </a> <div><a href="/profile/rajiv_kale" title="Newbie rajiv_kale" class="rated-user user-gray">rajiv_kale</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601975" href="?#comment-601975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601975" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601975" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="758545" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601975"> <div class="moveup"> <div class="ttypography"><p>Good editorial. I especially liked those behind stories.</p></div> </div> </div> <div class="reply info"> <a class="comment-601975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601975"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601992" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601992" href="?#comment-601992" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601992" class="CommentVoteFrame" data-commentRating="8" 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;">+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-601992"> <div class="moveup"> <div class="ttypography"><p>My E looks very different, now I'm wondering if it's correct.</p><p>Let's focus only on one big strongly connected component. For each vertex $$$V$$$ all the vertices which point to $$$V$$$ are ordered in a path. So, maybe it's possible to somehow form a cycle from all the vertices from the SCC. Let's take any vertex $$$V$$$. Now, from all the vertices which point to the $$$V$$$ let's take the last one on this path, let's call it $$$U$$$. Fix $$$U$$$ before $$$V$$$ on this cycle. Now, in the same manner, find a vertex that will be before $$$U$$$. And so on until we have a full cycle. My guess is that it's correct and that after this process which vertex points to some interval on the cycle which starts in this vertex. With such a form of the graph, we can easily calculate the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-601992 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601992 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601992"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602013" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602013" href="?#comment-602013" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602013" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-62" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-602013"> <div class="moveup"> <div class="ttypography"><p>Im not gonna lie but div2 was not interesting at all, problems D and E just required some basic observation. I hope future rounds require some more algorithmic skills to solve D and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-602013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602013"> <li> <div class="comment"> <table class="comment-table" commentId="602039" commentParentId="602013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602039" href="?#comment-602039" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602039" class="CommentVoteFrame" data-commentRating="100" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+100</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602039"> <div class="moveup"> <div class="ttypography"><p>How come did you only solve A then?</p></div> </div> </div> <div class="reply info"> <a class="comment-602039 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602039 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602039"> <li> <div class="comment"> <table class="comment-table" commentId="602102" commentParentId="602039"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602102" href="?#comment-602102" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602039" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602102" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-40" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602102"> <div class="moveup"> <div class="ttypography"><p>The point is not how many problems I solved or not but about the quality of problems, pls dont divert issues like this. (btw that submission to A is after contest :p)</p></div> </div> </div> <div class="reply info"> <a class="comment-602102 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602102 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602102"> <li> <div class="comment"> <table class="comment-table" commentId="602128" commentParentId="602102"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602128" href="?#comment-602128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602102" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602128" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602128"> <div class="moveup"> <div class="ttypography"><p>OK, I'm sorry.</p><p>Well, I thought they were good :D. It's kinda subjective. Who's to say &quot;making observations&quot; is worse than &quot;algorithmic skills&quot;? I don't think it's so much about &quot;quality of problems&quot; than &quot;style of problems&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-602128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602128"> <li> <div class="comment"> <table class="comment-table" commentId="602144" commentParentId="602128"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602144" href="?#comment-602144" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602144" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602144"> <div class="moveup"> <div class="ttypography"><p>I agree it's about style problems and I also liked the problems today. However I do agree with <a class="rated-user user-black" href="/profile/bored69" title="Unrated, bored69">bored69</a> that imo too many problems are extremely short to code while relying solely on observation. While I know many people enjoy the short to code problems, it is called _code_forces after all, so I think the solution should be longer than 10 lines to solve the problem, and I would enjoy getting to use some standard algorithms more often as long as the problem is still not straight application</p></div> </div> </div> <div class="reply info"> <a class="comment-602144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602144"> <li> <div class="comment"> <table class="comment-table" commentId="602407" commentParentId="602144"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lessmeaning" style="position: relative;"> <img src='https://userpic.codeforces.org/400632/avatar/4aeb556dedbc357a.jpg'/> </a> <div><a href="/profile/lessmeaning" title="Master lessmeaning" class="rated-user user-orange">lessmeaning</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602407" href="?#comment-602407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602144" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602407" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="400632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602407"> <div class="moveup"> <div class="ttypography"><p>Another Radewoosh's pawn</p></div> </div> </div> <div class="reply info"> <a class="comment-602407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602407"> <li> <div class="comment"> <table class="comment-table" commentId="602903" commentParentId="602407"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602903" href="?#comment-602903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602407" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602903" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602903"> <div class="moveup"> <div class="ttypography"><p>Maybe Radewoosh is my pawn ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-602903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602903"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602017" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602017" href="?#comment-602017" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602017" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602017"> <div class="moveup"> <div class="ttypography"><p>In Div 2-D explanation, I am not able to understand e-l+m part. Can someone help? </p></div> </div> </div> <div class="reply info"> <a class="comment-602017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602017"> <li> <div class="comment"> <table class="comment-table" commentId="602185" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602185" href="?#comment-602185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602185" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602185"> <div class="moveup"> <div class="ttypography"><p>The key construction in the editorial is that for every leaf i, the edge between i and its parent is xor(path(root,parent(i))). This construction guarantees different weights with one exception, what if multiple leaves have same parent? In that case we'll have only one extra distinct weight for all leaves with a common parent. So instead of including weights for all the leaves, we'll include weights only for their parents. Hence, first assume all edges as distinct and include them all(e) , then remove all leaves(l) and finally add those parents (which are non-leaf nodes with atleast one child as leaf (m)). So, we get e-l+m.</p></div> </div> </div> <div class="reply info"> <a class="comment-602185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602185"> <li> <div class="comment"> <table class="comment-table" commentId="602260" commentParentId="602185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602260" href="?#comment-602260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602185" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602260"> <div class="moveup"> <div class="ttypography"><p>I checked your solution. I am having some doubts. 1- Why did you choose your node as the vertex with a maximum degree? 2- The minimum f condition says if only odd paths are there, the minimum f is 1. forex. like 1--2--3--4(-- is an edge), how only one number can ensure bitwise XOR of 0?</p></div> </div> </div> <div class="reply info"> <a class="comment-602260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602260"> <li> <div class="comment"> <table class="comment-table" commentId="602286" commentParentId="602260"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602286" href="?#comment-602286" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602260" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602286" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602286"> <div class="moveup"> <div class="ttypography"><ol> <li>I had a different approach when I started coding, so i start with that node with maximum degre. In my approach, the necessary condition is that root node should not be leaf, if it is I'll not count one leaf in my dfs leading to a wrong answer.</li> <li>Minimum condition for f is, all leaf nodes should be at a distance of same parity from root, so that every pair of leaves are separated by even no. Of edges.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-602286 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602286 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602286"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602209" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602209" href="?#comment-602209" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602209" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602209"> <div class="moveup"> <div class="ttypography"><p>What about the case when edges with same weight are counted twice? In the picture Observation 3, the edges (1)-(2) and (2)-(6) should have the same weight. But the formula will count them as separate weights. Can someone please explain&gt;</p></div> </div> </div> <div class="reply info"> <a class="comment-602209 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602209 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602209"> <li> <div class="comment"> <table class="comment-table" commentId="602232" commentParentId="602209"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:52">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602232" href="?#comment-602232" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602209" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602232" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602232"> <div class="moveup"> <div class="ttypography"><p>No, it won't be counted twice. edges 1-2 and 2-6 are first removed by subtracting l (e-l) and then added once for their common parent 2(non-leaf node with 2 leaves) through m (e-l+m)</p></div> </div> </div> <div class="reply info"> <a class="comment-602232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602232"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602029" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaaven" style="position: relative;"> <img src='https://userpic.codeforces.org/851917/avatar/442eaf7f5f3f896b.jpg'/> </a> <div><a href="/profile/vaaven" title="Master vaaven" class="rated-user user-orange">vaaven</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602029" href="?#comment-602029" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602029" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="851917" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602029"> <div class="moveup"> <div class="ttypography"><p>Thank you for interesting and hard problems, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a>!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-602029 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602029 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602029"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602042" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602042" href="?#comment-602042" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602042" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602042" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602042"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1338/problem/B" title="Codeforces Round 633 (Div. 1)">1338B - Edge Weight Assignment</a> Dont get it how the construction works at all. Should't there be some recursion as we do a dfs? How/where do we start, and what to do in &quot;each step&quot;, assuming there are steps?</p></div> </div> </div> <div class="reply info"> <a class="comment-602042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602042"> <li> <div class="comment"> <table class="comment-table" commentId="602203" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AdsT" style="position: relative;"> <img src='https://userpic.codeforces.org/639570/avatar/f12b9c2694f9e204.jpg'/> </a> <div><a href="/profile/AdsT" title="Expert AdsT" class="rated-user user-blue">AdsT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602203" href="?#comment-602203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602203" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="639570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602203"> <div class="moveup"> <div class="ttypography"><p>I agree, everyone seemed to have just done the same thing, take one from the back and one from the front, I just am not able to prove this. How do I come to this conclusion?</p></div> </div> </div> <div class="reply info"> <a class="comment-602203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602203"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602348" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602348" href="?#comment-602348" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602348" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602348"> <div class="moveup"> <div class="ttypography"><p>This is a way that I came up with to always satisfy 3 distinct colors for every tree.</p><p>Choose a leaf (called $$$u$$$) and choose the connected node with this leaf (called $$$r$$$ and obviously this node won't be a leaf, as $$$n &gt;= 3$$$) as the root.</p><p>What we are going to construct is we are trying to make: $$$ xor(path(r, v)) = xor(path(r, u)) $$$ for every leaf $$$v$$$. Because when $$$ xor(path(r, v)) = xor(path(r, u)) $$$ then $$$ xor(path(r, v_1)) = xor(path(r, v_2)) ( = xor(path(r, u)))$$$ for every pair of leaves.</p><p>We have $$$xor(path(r, v_1)) = xor(path(r, v_2)) $$$ $$$\Leftrightarrow (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_1))) = (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_2)))$$$ $$$\Leftrightarrow xor(path(lca(v_1, v_2), v_1)) = xor(path(lca(v_1, v_2), v_2)) \Rightarrow$$$ Satisfy the condition</p><p>So here is what I do:</p> <ol> <li>Let the edge between $$$r$$$ and $$$u$$$ have weight $$$1$$$.</li> <li>We dfs from $$$r$$$, save the prefix $$$xor$$$ value from $$$r$$$ to the node $$$p$$$ we are at and dfs to node children $$$v$$$ of $$$p$$$:</li> </ol> <ul> <li>If $$$v$$$ is a leaf, then we need to assign this edge so that the prefix $$$xor$$$ value will be equal to $$$1$$$ ($$$ = xor(path(r, u))$$$).</li> <li>If $$$v$$$ is not a leaf, then we assign $$$2$$$ to that edge. Why? Because we need to get rid of the case when the prefix $$$xor$$$ value at node $$$p$$$ (parent of leaf $$$v$$$, for example) is equal to $$$1$$$ ($$$ = xor(path(r, u))$$$) and whatever we assign $$$edge(p, v)$$$ we cannot make the prefix $$$xor$$$ value at leaf $$$v$$$ equal to $$$1$$$ anymore.</li> </ul><p>P/s: Ask me anything that you may not understand ^^. </p></div> </div> </div> <div class="reply info"> <a class="comment-602348 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602348 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602348"> <li> <div class="comment"> <table class="comment-table" commentId="602440" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602440" href="?#comment-602440" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602440" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602440"> <div class="moveup"> <div class="ttypography"><p>Thanks!</p><p>Now I think the key observation to come up with all of this is the parity of distances of three leafs.</p><p>$$$parity(dist(l1,l2)) \oplus parity(dist(l1,l3)) = parity(dist(l2,l3))$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-602440 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602440 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602440"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603442" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603442" href="?#comment-603442" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603442" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603442"> <div class="moveup"> <div class="ttypography"><p>I didnt get the part where you assign 2 to the edge that is not a leaf.</p></div> </div> </div> <div class="reply info"> <a class="comment-603442 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603442 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603442"> <li> <div class="comment"> <table class="comment-table" commentId="603446" commentParentId="603442"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603446" href="?#comment-603446" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603442" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603446"> <div class="moveup"> <div class="ttypography"><p>Consider all the edges which not connect any leaf are assigned $$$2$$$, then all the prefix $$$xor$$$ value at node $$$p$$$ (not a leaf) will be either $$$...000$$$ or $$$...010$$$. So when we go to a leaf we can assign a possible value to make the prefix $$$xor$$$ equal to $$$...001$$$. </p><p>Suppose we don't assign $$$2$$$ but $$$1$$$ or $$$3$$$ then there will be the case when at node $$$p$$$ (not a leaf but have a leaf child) the prefix $$$xor$$$ may be $$$...001$$$ and go to node $$$v$$$ (the leaf child of $$$p$$$) whether we assign the edge $$$1$$$, $$$2$$$ or $$$3$$$ then the prefix $$$xor$$$ can't be $$$...001$$$ anymore.</p><p>Sorry for my bad English !</p></div> </div> </div> <div class="reply info"> <a class="comment-603446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603446"> <li> <div class="comment"> <table class="comment-table" commentId="603451" commentParentId="603446"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603451" href="?#comment-603451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603446" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603451" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603451"> <div class="moveup"> <div class="ttypography"><p>Thanks to your quick reply,I am able to understand it.Can you please suggest some resources or something that would help me in solving problem cause' I am only able to solve upto problem c everytime?</p></div> </div> </div> <div class="reply info"> <a class="comment-603451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603451"> <li> <div class="comment"> <table class="comment-table" commentId="603456" commentParentId="603451"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603456" href="?#comment-603456" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603451" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603456" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603456"> <div class="moveup"> <div class="ttypography"><p>My suggestions: Solve problems and reflect upon what you have done wrong ... or what's observation you missed (And note them back obviously) ... or new algorithms (search and read for them and do 3 — 5 problems about that topic). Sometimes algorithm have signs, try to see that.</p><p>P/s: It's my own opinion anyway. Good luck &lt;3.</p></div> </div> </div> <div class="reply info"> <a class="comment-603456 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603456 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603456"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606855" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Darooha" style="position: relative;"> <img src='https://userpic.codeforces.org/27157/avatar/c4be2a4212ec87ed.jpg'/> </a> <div><a href="/profile/Darooha" title="Pupil Darooha" class="rated-user user-green">Darooha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606855" href="?#comment-606855" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606855" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="27157" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-606855"> <div class="moveup"> <div class="ttypography"><p>To everybody: The editorial has this update. It makes the problem much simpler:</p><p>(Update) There is an another way to approach, provided by Darooha.</p><p>If you label vertices instead of edges where all leaves have same label and none of neighbors have same label, then you can consider edge weight as xor of two vertices' labels, so this is basically equivalent to original problem.</p><p>Now for minimum, you can see that labelling 0 to leaves, and 1,2 to non-leaves are enough, so you can prove minimum value of f is at most 3. In same manner, you can try parity checking to check if f value can be 1 or not.</p><p>For maximum, assign 0 to all leaves and assign all different values(21,22,...) to non-leaf vertices, then you can see all edge weights(except leaves connected to same vertex) are different.</p></div> </div> </div> <div class="reply info"> <a class="comment-606855 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606855 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606855"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rojansudev700" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rojansudev700" title="Newbie rojansudev700" class="rated-user user-gray">rojansudev700</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602066" href="?#comment-602066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1236502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602066"> <div class="moveup"> <div class="ttypography"><p>Can anybody please explain problem A and its editorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-602066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602066"> <li> <div class="comment"> <table class="comment-table" commentId="602098" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602098" href="?#comment-602098" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602098"> <div class="moveup"> <div class="ttypography"><p>You may refer to the picture in the editorial. In this picture, if you put the red one in, you will find there is only one way to fill it( also described in the picture). Hence, since there are N different ways for putting the red one in, the answer is simply N.</p></div> </div> </div> <div class="reply info"> <a class="comment-602098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602098"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602157" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Apr/12/2020 21:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602157" href="?#comment-602157" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602157" 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-602157"> <div class="moveup"> <div class="ttypography"><p>Consider you want to find the answer for shape with size N. Let's say you put a Vertical diamond initially then places of all other diamonds are decided. So this is 1 way to put diamonds.</p><p>The other way is to put two horizontal diamonds on top left and bottom left and then we are have to find ways to puts diamonds in a shape of size N-1.</p><p>Ans(i) = 1 + Ans(i-1) <br /> {1 for the way in which vertical diamond is placed on the leftmost position}</p><p>Ans(i) = 1 + Ans(i-1) = i, given ans(1) =1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602157"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602093" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bayweiheng" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bayweiheng" title="Grandmaster bayweiheng" class="rated-user user-red">bayweiheng</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602093" href="?#comment-602093" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602093" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="533715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602093"> <div class="moveup"> <div class="ttypography"><p>In Div1E, How can we calculate the contribution from vertices with no indegree? If v has no indegree, then dis(u,v) is known but how do we find dis(v,u)? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-602093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602093"> <li> <div class="comment"> <table class="comment-table" commentId="602110" commentParentId="602093"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602110" href="?#comment-602110" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602093" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602110" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602110"> <div class="moveup"> <div class="ttypography"><p>If $$$u$$$ has no in-degree then $$$dis(u,v)=1, dis(v,u)=614n$$$ for all $$$u\neq v$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602110 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602110 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602110"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602145" href="?#comment-602145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602145" 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="602145" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602145"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">E intuition?</b><div class="spoiler-content" style="display: none;"><p>Assume that all nodes have positive in-degree. Then we can arrange the nodes in a cycle $$$c_0,c_1,\ldots, c_{n-1}$$$ such that $$$c_i$$$ has edges to $$$c_{i+1},c_{i+2},\ldots,c_{(i+out(i))\pmod{n}}$$$ where $$$out(i)$$$ denotes the out-degree of node $$$c_i$$$. To find this cycle, start with any vertex $$$x$$$ and topologically sort $$$in(x)$$$. Then repeat with the last node of $$$in(x)$$$ (with respect to the sorted order).</p><p>For all $$$i$$$, $$$out(i)&gt;0$$$ and $$$out(i)\le out((i+1)\pmod{n})+1$$$. Suppose that $$$i&lt;j$$$. Then $$$out(i)+i\le out(j)+j$$$ and the distance from $$$c_j$$$ to $$$c_i$$$ is three iff $$$out(i)+i=out(j)+j$$$. Otherwise, it's one or two.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-602145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602145"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602151" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misqwerty" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/misqwerty" title="Newbie misqwerty" class="rated-user user-gray">misqwerty</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602151" href="?#comment-602151" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602151" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="727011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602151"> <div class="moveup"> <div class="ttypography"><p>Do anyone else other than me recognize this submission as a hack for a hack and there were two successful hacking attempts. That's a <strong>cheat</strong>. <a href="/contest/1339/submission/76401969" title="Submission 76401969 by SIBshaan">76401969</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602151 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602151 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602151"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602165" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602165" href="?#comment-602165" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602165" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602165"> <div class="moveup"> <div class="ttypography"><p>how to find editorial in english for Atcoder Begginer contest 162 on their website it's in japanese..</p></div> </div> </div> <div class="reply info"> <a class="comment-602165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602165"> <li> <div class="comment"> <table class="comment-table" commentId="602170" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:39">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602170" href="?#comment-602170" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602170" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602170"> <div class="moveup"> <div class="ttypography"><p>Pay attention to the red line written on the first page of the Japanese editorial .</p></div> </div> </div> <div class="reply info"> <a class="comment-602170 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602170 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602170"> <li> <div class="comment"> <table class="comment-table" commentId="602195" commentParentId="602170"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602195" href="?#comment-602195" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602170" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602195" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602195"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602195 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602195 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602195"> <li> <div class="comment"> <table class="comment-table" commentId="602248" commentParentId="602195"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602248" href="?#comment-602248" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602195" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602248" 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-602248"> <div class="moveup"> <div class="ttypography"><p>I've solved A,B,C,D if you want, i can tell u how to solve them</p></div> </div> </div> <div class="reply info"> <a class="comment-602248 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602248 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602248"> <li> <div class="comment"> <table class="comment-table" commentId="602255" commentParentId="602248"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602255" href="?#comment-602255" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602248" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602255" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602255" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602255"> <div class="moveup"> <div class="ttypography"><p>please tell me how you solved D</p></div> </div> </div> <div class="reply info"> <a class="comment-602255 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602255 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602255"> <li> <div class="comment"> <table class="comment-table" commentId="602270" commentParentId="602255"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602270" href="?#comment-602270" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602255" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602270" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602270" 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-602270"> <div class="moveup"> <div class="ttypography"><p>So you gonna fix i and k such that S[i] != S[k]. So in the range [i + 1, k — 1] you should find the number of characters C different from S[i] as well as S[j]. So, for example, if S[i] = 'R' and S[k] = 'G', C = 'B'. So these different characters can be found using segment tree, maybe there is other method too. Also you should check for the second condition, if (k — i) % 2 == 0 and S[(i + k) / 2] == c, you gonna decrement that number by one.</p></div> </div> </div> <div class="reply info"> <a class="comment-602270 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602270 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602270"> <li> <div class="comment"> <table class="comment-table" commentId="602272" commentParentId="602270"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602272" href="?#comment-602272" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602270" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602272" 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-602272"> <div class="moveup"> <div class="ttypography"><p>That's my solution, but I think there is a better solution described in the following video: <a href="https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s">https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602272"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602172" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602172" href="?#comment-602172" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602172" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602172"> <div class="moveup"> <div class="ttypography"><p>Btw, why ask this here xD</p></div> </div> </div> <div class="reply info"> <a class="comment-602172 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602172 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602172"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602167" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602167" href="?#comment-602167" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602167" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602167"> <div class="moveup"> <div class="ttypography"><p>Could someone elaborate a bit more the intuition behind Div1D and how to implement it?</p></div> </div> </div> <div class="reply info"> <a class="comment-602167 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602167 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602167"> <li> <div class="comment"> <table class="comment-table" commentId="602265" commentParentId="602167"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602265" href="?#comment-602265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602167" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602265" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602265" class="CommentVoteFrame" data-commentRating="42" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+42</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602265"> <div class="moveup"> <div class="ttypography"><p>I approached this problem by considering what happens if we only consider the minimum connected subgraph containing the answer, where the answer is the set of nodes $$$S$$$ that form the nested rubber bands. First, consider each $$$v\in S$$$ as a circle, so we have $$$|S|$$$ nested circles. The other vertices of this minimum connected subgraph must contribute to connecting two or more circles, and we can consider them as line segments. </p><p>Colour the line segments red and the circles blue. Then, we'll see that the red vertices lie on a path, because we can trace out a path in this alternate representation of the tree. Furthermore, the blue vertices form an independent set, and each is adjacent to at least one red vertex.</p><p>DP states:</p><p>For each state, I suppose that the red vertices lie on a path in the subtree rooted at u with one endpoint at u.</p> <ul> <li><p>take[u] = number of blue vertices if u is blue</p></li> <li><p>skip[u] = number of blue vertices if u is red</p></li> </ul><p>DP transitions:</p> <ul> <li><p><code>take[u] = max(1 + skip[child])</code>. Since we're interested in a path, we take the max.</p></li> <li><p><code>skip[u] = max(#children-1 + max(take[child], skip[child]))</code>. If we colour u red, then we can colour all its uncoloured neighbours blue, but we still want to be able to choose for the next node in the path.</p></li> </ul><p>To get the answer, consider a path rooted at u. We need to know the best two values of <code>take[child]</code> and <code>max(take[child], skip[child])</code> to find the answer for such a path.</p><p>I'm sure you could fit the dp and get the solution in one dfs function, but here's my rather long and verbose code: <a href="https://codeforces.com/contest/1338/submission/76420228">https://codeforces.com/contest/1338/submission/76420228</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602265"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602182" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gouravmajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1380497/avatar/470f8f4adfac9b5d.jpg'/> </a> <div><a href="/profile/gouravmajee" title="Newbie gouravmajee" class="rated-user user-gray">gouravmajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602182" href="?#comment-602182" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602182" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1380497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602182"> <div class="moveup"> <div class="ttypography"><p>this was my first contest :) I passed question 1. </p></div> </div> </div> <div class="reply info"> <a class="comment-602182 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602182 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602182"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602191" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aid" style="position: relative;"> <img src='https://userpic.codeforces.org/106240/avatar/ab90218e19d9e731.jpg'/> </a> <div><a href="/profile/aid" title="International Grandmaster aid" class="rated-user user-red">aid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602191" href="?#comment-602191" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602191" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="106240" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602191"> <div class="moveup"> <div class="ttypography"><p>$$$O(n^2\log(n))$$$ can be squeezed in E: <a href="/contest/1338/submission/76419686" title="Submission 76419686 by aid">76419686</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-602191 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602191 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602191"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602210" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cdc.biobot" style="position: relative;"> <img src='https://userpic.codeforces.org/152957/avatar/23e3d83914fae0f6.jpg'/> </a> <div><a href="/profile/cdc.biobot" title="Newbie cdc.biobot" class="rated-user user-gray">cdc.biobot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602210" href="?#comment-602210" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602210" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602210" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="152957" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602210"> <div class="moveup"> <div class="ttypography"><p>I beg your pardon, but I think problem statement of div2A should have been a bit clearer in explaining the term 'covering differently'. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-602210 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602210 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602210"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602211" href="?#comment-602211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602211" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602211"> <div class="moveup"> <div class="ttypography"><p>In Div2 D for finding the maximum f value, what is the proof that there is no other construction possible that can possibly have more distinct weights? For example, consider a tree with the non-leaf nodes having degree 4. In the observation 3 picture, we can add to node 2, a replica structure of its child node 3. That will make node 2's degree 4. How to prove for this case(and in general) that the maximum value of f will not exceed e-l+m?</p></div> </div> </div> <div class="reply info"> <a class="comment-602211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602211"> <li> <div class="comment"> <table class="comment-table" commentId="602241" commentParentId="602211"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602241" href="?#comment-602241" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602211" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602241" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602241"> <div class="moveup"> <div class="ttypography"><p>Because that's the upper bound of the value.</p><p>Every edge that isn't adjacent to a leaf doesn't matter. Edges for leaves that are adjacent to the same non-leaf vertex need to be equal. That can be counted as in the editorial because — (leaves — non-leaf vertex adjacent to a leaf) is exactly the number of edges to leaves that are free to receive values.</p></div> </div> </div> <div class="reply info"> <a class="comment-602241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602241"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602221" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602221" href="?#comment-602221" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602221" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602221"> <div class="moveup"> <div class="ttypography"><p>hi..what is the maximum time in which it's good to solve div2 — A and B.. because i'm practicing only DIV2 A and B question in virtual contest..and still took more than 1 h to solve both...some time i failed to solve B.. Thanks in advance..</p></div> </div> </div> <div class="reply info"> <a class="comment-602221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602221"> <li> <div class="comment"> <table class="comment-table" commentId="602497" commentParentId="602221"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602497" href="?#comment-602497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602221" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602497"> <div class="moveup"> <div class="ttypography"><p>See this round was tough, but I think top coders take max 15 min for both, at my rating I think even 30 mins would be fine and for you, 45-60 min is the max you should ideally take</p></div> </div> </div> <div class="reply info"> <a class="comment-602497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602497"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602236" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Muhammad98" style="position: relative;"> <img src='https://userpic.codeforces.org/697747/avatar/2c13087bfd195af6.jpg'/> </a> <div><a href="/profile/Muhammad98" title="Specialist Muhammad98" class="rated-user user-cyan">Muhammad98</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602236" href="?#comment-602236" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="697747" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602236"> <div class="moveup"> <div class="ttypography"><p>The only Div2A that I couldn't solve during the round XD</p></div> </div> </div> <div class="reply info"> <a class="comment-602236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602236"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602238" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602238" href="?#comment-602238" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602238" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602238"> <div class="moveup"> <div class="ttypography"><p>Nice editorial and pictures! <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> One suggestion: It'll be easier to read d1E if you use lowercase letters for vertices and upper case letters for sets.</p></div> </div> </div> <div class="reply info"> <a class="comment-602238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602238"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gjaiswal108" style="position: relative;"> <img src='https://userpic.codeforces.org/756634/avatar/f398cd162ff7d60f.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/gjaiswal108" title="Expert gjaiswal108" class="rated-user user-blue">gjaiswal108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602251" href="?#comment-602251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602251" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756634" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602251"> <div class="moveup"> <div class="ttypography"><p><code>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this</code></p><p>Can anyone tell me what is meaning of OEIS in the story of D2E ?</p></div> </div> </div> <div class="reply info"> <a class="comment-602251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602251"> <li> <div class="comment"> <table class="comment-table" commentId="602259" commentParentId="602251"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/blitzitout" style="position: relative;"> <img src='https://userpic.codeforces.org/505681/avatar/39b2976ffc156007.jpg'/> </a> <div><a href="/profile/blitzitout" title="Expert blitzitout" class="rated-user user-blue">blitzitout</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602259" href="?#comment-602259" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602251" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602259" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602259" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="505681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602259"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/">This</a> is where you can find insights/recurrences of random sequences.</p></div> </div> </div> <div class="reply info"> <a class="comment-602259 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602259 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602259"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602252" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T-REXX" style="position: relative;"> <img src='https://userpic.codeforces.org/455170/avatar/f7f08af680e3156f.jpg'/> </a> <div><a href="/profile/T-REXX" title="Pupil T-REXX" class="rated-user user-green">T-REXX</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602252" href="?#comment-602252" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602252" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="455170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602252"> <div class="moveup"> <div class="ttypography"><p>I tried solving div2C by iterating through the array, whenever a[i]&gt;a[i+1] I added to all j=i+1 and j&lt;n lowest power of 2 possible to make it a[i]&lt;=a[i+1]. Lowest power was calculated using a vector of powers of 2. But it does not work, and I am unable to find out why. Can anyone help?</p></div> </div> </div> <div class="reply info"> <a class="comment-602252 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602252 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602252"> <li> <div class="comment"> <table class="comment-table" commentId="602471" commentParentId="602252"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bryceShakeair" style="position: relative;"> <img src='https://userpic.codeforces.org/872528/avatar/f8595cfd5dbfc474.jpg'/> </a> <div><a href="/profile/bryceShakeair" title="Specialist bryceShakeair" class="rated-user user-cyan">bryceShakeair</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602471" href="?#comment-602471" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602252" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602471" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872528" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602471"> <div class="moveup"> <div class="ttypography"><p>try 1 0 1 0 1 0 The optimal answer is x = 1 i.e. select indexes 2 , 4 ,6 you get 1 1 1 1 1 1 I hope that is clear </p></div> </div> </div> <div class="reply info"> <a class="comment-602471 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602471 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602471"> <li> <div class="comment"> <table class="comment-table" commentId="604684" commentParentId="602471"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604684" href="?#comment-604684" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602471" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604684" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604684"> <div class="moveup"> <div class="ttypography"><p>Thanks. </p></div> </div> </div> <div class="reply info"> <a class="comment-604684 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604684 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604684"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602282" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant_raja" style="position: relative;"> <img src='https://userpic.codeforces.org/742080/avatar/101f3740a4030218.jpg'/> </a> <div><a href="/profile/nishant_raja" title="Pupil nishant_raja" class="rated-user user-green">nishant_raja</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602282" href="?#comment-602282" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602282" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742080" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602282"> <div class="moveup"> <div class="ttypography"><p>Can anyone briefly explain the problem &quot;Powered Addition&quot;, I mean full approach and walk through an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-602282 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602282 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602282"> <li> <div class="comment"> <table class="comment-table" commentId="602498" commentParentId="602282"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jbs1jbs1jbs1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/jbs1jbs1jbs1" title="Specialist jbs1jbs1jbs1" class="rated-user user-cyan">jbs1jbs1jbs1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602498" href="?#comment-602498" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602282" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602498" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602498"> <div class="moveup"> <div class="ttypography"><p>My approach was as follows:</p><p>Let's say that the list is <code>[1, 7, 6, 5]</code>. We go through and we look at all the pairs <code>(a[i], a[i+1])</code>. We start with <code>(1,7)</code>. It satisfies the property of being non-decreasing, so we do nothing. Next, we go to <code>(7, 6)</code>. <code>6 &lt; 7</code>, meaning we have to add something to &quot;6&quot; to make it bigger. I assert (and will explain below the reason why), that it is possible and optimal to convert the &quot;6&quot; into a &quot;7&quot;. The list then becomes <code>[1, 7, 7, 5]</code>. Next, we look at the final pair <code>(7, 5)</code> and do the same: convert the &quot;5&quot; to a &quot;7&quot;, so that the final list becomes [1, 7, 7, 7].</p><p>When we convert a pair (a, b) to the pair (a, a), it means that we need to add some quantity (a-b) to it. If that quantity is 18, for example, then we can do this with 16 + 2 = 2^4 + 2^1. If that quantity is 15, we can do this with 2^0 + 2^1 + 2^2 + 2^3. In general, there is exactly one way to do the addition of distinct powers of 2 to get from one number to another.</p><p>You can find out which powers of 2 you need to add together by converting the difference into binary. The definition of binary is that where there is a &quot;1&quot; you can add the relevant power of 2.</p><p>In any case, I'm just saying that it is always <strong>possible</strong> to do this, and it doesn't matter what the exact powers of 2 are, you just need to know what the biggest power of 2 needed will be. This is because if you're using a bigger power of 2, for example 2^5, it means that seconds 1, 2, 3, 4, 5, 6 have already happened, so you could have, in the past, added 2^0, 2^1, 2^2, 2^3, 2^4 if you needed to do so.</p><p>The biggest power of 2 needed can be worked out by taking the logarithm base 2 of the difference, and then rounding down.</p><p>The code would then be something like this:</p> <pre><code>max_power_found = -1 for i in range(len(a) - 1): if a[i + 1] &lt; a[i]: difference = a[i] - a[i + 1] biggest_power = floor(log2(difference)) max_power_found = max(max_power_found, biggest_power) a[i + 1] = a[i] print(max_power_found + 1) </code></pre><p>Note that I initialise <code>max_power_found</code> to <code>-1</code> so that at the end, if nothing has happened because the array was already non-decreasing, it becomes <code>0</code> when you add 1.</p><p>Note also that even though we don't need to output the final array, I have the line <code>a[i + 1] = a[i]</code>. This is because the next pair needs to know about the change we just made.</p><p>There are <code>(n-1)</code> possible values of <code>i</code>, and for each one we do some constant time computation (logarithm base 2 is very fast), this is an O(n) solution.</p><p>Note that even if you didn't know about logarithms, you could probably do it very quickly because log2(10^5) is very small (though I haven't tested to make sure this doesn't TLE):</p> <pre><code>def biggest_power_needed(difference): # Outputs -1 if difference is 0. answer = -1 total = 0 while total &lt; difference: answer++ total += pow(2, answer) if total == difference: return answer else: return answer - 1 </code></pre><p>Again, we do <code>answer - 1</code> because we can use the smaller powers of 2 to increase it to exactly equal the difference.</p></div> </div> </div> <div class="reply info"> <a class="comment-602498 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602498 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602498"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shivamsaluja20" style="position: relative;"> <img src='https://userpic.codeforces.org/820036/avatar/92e6360dd7bc5c3d.jpg'/> </a> <div><a href="/profile/shivamsaluja20" title="Specialist shivamsaluja20" class="rated-user user-cyan">shivamsaluja20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602291" href="?#comment-602291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602291" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="820036" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602291"> <div class="moveup"> <div class="ttypography"><p>For the first time for problem A, it took me around 50 minutes to figure out and ironically that was the easiest one liner solution possible. Take the input and print it xD.</p></div> </div> </div> <div class="reply info"> <a class="comment-602291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EleCursity" style="position: relative;"> <img src='https://userpic.codeforces.org/388600/avatar/c667ca12cb3a5eb2.jpg'/> </a> <div><a href="/profile/EleCursity" title="Expert EleCursity" class="rated-user user-blue">EleCursity</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602292" href="?#comment-602292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602292" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="388600" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602292"> <div class="moveup"> <div class="ttypography"><p>Nice Editorial and nice problems. In <strong>div2E/div1C</strong> .I've found a strange pattern for the bits in the n-th triple . but I can't manage to code it during the contest. this is my code <a href="/contest/1339/submission/76432679" title="Submission 76432679 by EleCursity">76432679</a> .</p></div> </div> </div> <div class="reply info"> <a class="comment-602292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602297" href="?#comment-602297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602297"> <div class="moveup"> <div class="ttypography"><p>2D, I understand nothing, damn constructive problems and damn gap between C and D</p><p>&quot;Observation 1. You can prove that minimum value of f is at most 3, by following construction;&quot;</p><p>Well, how do we know there is no other construction where we would have 4 or more?</p><p>&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?</p><p>&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose</p></div> </div> </div> <div class="reply info"> <a class="comment-602297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602297"> <li> <div class="comment"> <table class="comment-table" commentId="602302" commentParentId="602297"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602302" href="?#comment-602302" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602297" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602302" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-602302"> <div class="moveup"> <div class="ttypography"><p>&quot;Well, how do we know there is no other construction where we would have 4 or more?&quot; The problem is asking for the minimum, there is a construction where $$$3$$$ is possible so the minimum is never greater than $$$3$$$</p><p>&quot;&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?&quot; Because we decided that that's how the construction should look like. Another example of a construction which would work is edges connecting a leaf having a weight of $$$2$$$ or $$$3$$$ depending on the parity leaf's depth and all other edges having a weight of $$$1$$$.</p><p>&quot;&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose&quot; Here's a proof: Notice that we can consider each bit separately and then an assignment works if the condition is satisfied for all bits. Let's say we choose numbers $$$a$$$ and $$$b$$$. If both $$$a$$$ and $$$b$$$ have some bit set to $$$1$$$ then that is the same as the $$$f=1$$$ case. If there is no bit which both $$$a$$$ and $$$b$$$ have set to 1 then that means that there is a bit which $$$a$$$ has set to $$$1$$$ and $$$b$$$ has set to $$$0$$$ and that there is a bit which $$$a$$$ has set to $$$0$$$ and $$$b$$$ has set to $$$1$$$, so each path needs to have an even number of both $$$a$$$ and $$$b$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602302 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602302 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602302"> <li> <div class="comment"> <table class="comment-table" commentId="602304" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 02:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602304" href="?#comment-602304" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602304" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602304"> <div class="moveup"> <div class="ttypography"><p>1-2) Oh, so it was about describing a generic technique of assigning values, not about the specific tree on the picture. Then it makes more sense</p><p>3) The confusing part here was that I thought it was about the number of a and b in the whole tree, not on the requested path, and didn't understand why.</p><p>I'll reread it with this in mind</p><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602304"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603392" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 02:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603392" href="?#comment-603392" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603392" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603392" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603392"> <div class="moveup"> <div class="ttypography"><p>I've got how we come up with f=3 from the comments</p><p>However I still don't understand the same part in the editorial &quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>On the picture we have a string of non-leaves, all of which have degree 3. And all the leaves obviously have degree 1 So following this statement we're supposed to have the same weights for every edge connecting a non-leaf to a leaf on the picture. However, this is not the case. </p></div> </div> </div> <div class="reply info"> <a class="comment-603392 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603392 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603392"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/feecIe6418" style="position: relative;"> <img src='https://userpic.codeforces.org/699680/avatar/da9b3b3e29a8fe7b.jpg'/> </a> <div><a href="/profile/feecIe6418" title="International Grandmaster feecIe6418" class="rated-user user-red">feecIe6418</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 03:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602320" href="?#comment-602320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602320" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="699680" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602320"> <div class="moveup"> <div class="ttypography"><p>Finally become master in this round. I like the problems! Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-602320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602334" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602334" href="?#comment-602334" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602334" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602334"> <div class="moveup"> <div class="ttypography"><p><strong>HELP! Please</strong></p><p>Hi, everyone! My friends has some trouble in his solutions, He has submitted this solution <a href="/contest/1339/submission/76367506" title="Submission 76367506 by zhouxiaolun">76367506</a> during the round, However, after the system pending test, He did not get an AC, but still the Pretest passed. The score for this problem was not added to my friends. He has submitted totally the same code just now, <a href="/contest/1339/submission/76438866" title="Submission 76438866 by zhouxiaolun">76438866</a>, and get an AC. Why did this happen? It has effected on my friends ratings, Where can I find the administor to solve the trouble? (sorry for my poor english)</p></div> </div> </div> <div class="reply info"> <a class="comment-602334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602334"> <li> <div class="comment"> <table class="comment-table" commentId="602339" commentParentId="602334"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iynaur87" style="position: relative;"> <img src='https://userpic.codeforces.org/561459/avatar/4516a52f8c97c0c2.jpg'/> </a> <div><a href="/profile/iynaur87" title="Candidate Master iynaur87" class="rated-user user-violet">iynaur87</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602339" href="?#comment-602339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602334" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602339" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="561459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602339"> <div class="moveup"> <div class="ttypography"><p>Weired. You can Send a message to <a href="https://codeforces.com/profile/MikeMirzayanov">https://codeforces.com/profile/MikeMirzayanov</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602339"> <li> <div class="comment"> <table class="comment-table" commentId="602345" commentParentId="602339"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602345" href="?#comment-602345" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602339" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602345" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602345"> <div class="moveup"> <div class="ttypography"><p>Thank you! You are so kind!</p></div> </div> </div> <div class="reply info"> <a class="comment-602345 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602345 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602345"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602341" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Raghu150999" style="position: relative;"> <img src='https://userpic.codeforces.org/714738/avatar/992860969ab6c84.jpg'/> </a> <div><a href="/profile/Raghu150999" title="Expert Raghu150999" class="rated-user user-blue">Raghu150999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602341" href="?#comment-602341" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602341" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714738" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602341"> <div class="moveup"> <div class="ttypography"><p>Great editorial. Thanks a lot!</p></div> </div> </div> <div class="reply info"> <a class="comment-602341 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602341 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602341"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602383" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aspiriner" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/aspiriner" title="Expert aspiriner" class="rated-user user-blue">aspiriner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602383" href="?#comment-602383" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602383" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1393907" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602383"> <div class="moveup"> <div class="ttypography"><p>in the div 2 B </p><p>i do not understand what the 'Sort the list, and make an oscillation centered on middle element like picture below.' means.</p><p>i just dont know how to sort it and what should i do in the next step.</p><p>please help me!</p></div> </div> </div> <div class="reply info"> <a class="comment-602383 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602383 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602383"> <li> <div class="comment"> <table class="comment-table" commentId="602411" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shisuko" style="position: relative;"> <img src='https://userpic.codeforces.org/554313/avatar/42772b63e4542d29.jpg'/> </a> <div><a href="/profile/Shisuko" title="Candidate Master Shisuko" class="rated-user user-violet">Shisuko</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602411" href="?#comment-602411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602411" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="554313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602411"> <div class="moveup"> <div class="ttypography"><p>Sort the elements in ascending order. Then you go smallest-&gt;largest-&gt;second smallest-&gt;second largest... and so on. If you draw it on paper, you can see that the gaps are always getting smaller because it's a subset of the previous gap.</p></div> </div> </div> <div class="reply info"> <a class="comment-602411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602411"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602415" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602415" href="?#comment-602415" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602415" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602415"> <div class="moveup"> <div class="ttypography"><p>Imagine the problem is the same, but differences between pairs must be non increasing instead of non decreasing ( | a_ i — a_i-1 | &gt;= | a_i-1 — a_i-2 | ). If we solve this, we can just reverse the answer and we will get an answer to the original problem. </p><p>Now, imagine we start with the biggest element to the left. What number should we add next to maximize their difference? The smallest element. So we add it. After that, what number not yet added would maximize the difference of the pair? The second biggest element, and it is not hard to see it will be smaller or equal than the first pair. If we continue to do this, we can get an answer.</p><p>So to build it we just sort the initial array and then build it in the following way: a[N] , a[1] , a[N-1] , a[2] , a[N-2] , a[3] ... </p><p>After this, don't forget to reverse the answer to solve the original problem. </p><p>Submission: <a href="/contest/1339/submission/76418078" title="Submission 76418078 by Diegogrc">76418078</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602415 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602415 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602415"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602445" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xD." style="position: relative;"> <img src='https://userpic.codeforces.org/918251/avatar/298a43e5c9cee8f5.jpg'/> </a> <div><a href="/profile/xD." title="Pupil xD." class="rated-user user-green">xD.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602445" href="?#comment-602445" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602445" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602445" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="918251" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602445"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/aspiriner" title="Pupil aspiriner">aspiriner</a> <strong>This picture may help you</strong> <img alt=" " src="/predownloaded/43/9a/439a03f6fa84e1a1c14509dbd3d5c4c88ee8d5a3.php" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-602445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602445"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602386" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misty1999" style="position: relative;"> <img src='https://userpic.codeforces.org/461973/avatar/bda2e09a046c8571.jpg'/> </a> <div><a href="/profile/misty1999" title="Specialist misty1999" class="rated-user user-cyan">misty1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602386" href="?#comment-602386" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602386" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="461973" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602386"> <div class="moveup"> <div class="ttypography"><p>First I thought maximal independent set in div1D, but got Wrong Answer on pretest 4.</p></div> </div> </div> <div class="reply info"> <a class="comment-602386 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602386 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602386"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuber_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/820815/avatar/9d558886908a602d.jpg'/> </a> <div><a href="/profile/cuber_coder" title="Master cuber_coder" class="rated-user user-orange">cuber_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602400" href="?#comment-602400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602400" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="820815" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602400"> <div class="moveup"> <div class="ttypography"><p>Great problemset, a beautifully written editorial, no queueforces, strong pretests and quick system testing makes it a wonderful round! Hope to participate in more rounds authored by you in future!</p><p>P.S. : my most special round till date since I finally reached CM !</p></div> </div> </div> <div class="reply info"> <a class="comment-602400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602400"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602404" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602404" href="?#comment-602404" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602404" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602404"> <div class="moveup"> <div class="ttypography"><p>can someone explain div2-C,i am not able to understand the editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-602404 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602404 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602404"> <li> <div class="comment"> <table class="comment-table" commentId="602437" commentParentId="602404"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602437" href="?#comment-602437" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602404" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602437" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602437"> <div class="moveup"> <div class="ttypography"><p>first of all find the max difference between any two number (O(n)). then you just need to count number of digits in it. which can be done using log2 of that difference. note: ceil function is to be used for ex: 2.5 would be rounded off to 3.</p><p>here's my code(which is actually someone else but I copied it and modified a little, but is self explanatory )</p><p><a href="https://codeforces.com/contest/1339/submission/76446573">https://codeforces.com/contest/1339/submission/76446573</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602437 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602437 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602437"> <li> <div class="comment"> <table class="comment-table" commentId="602494" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602494" href="?#comment-602494" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602494" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602494"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/FinalBoss_" title="Pupil FinalBoss_">FinalBoss_</a> Can you please explain why did you add 1 in log2(dis+1) ?</p><p>I guess dis is the max number required to add.Why +1 ?My first submission was same but i didnt add 1 it got wa.</p></div> </div> </div> <div class="reply info"> <a class="comment-602494 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602494 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602494"> <li> <div class="comment"> <table class="comment-table" commentId="602546" commentParentId="602494"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602546" href="?#comment-602546" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602494" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602546" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602546"> <div class="moveup"> <div class="ttypography"><p>yes dis is the max number required to add. log2(dis+1) is done because... we were asked to find 2^(x-1).</p><p>in case all numbers are equal and dis is 0 or if array is already increasing and dis is still 0, then log(0) becomes undefined. Now since we don't need actual value but ceiling of it so adding 1 to dis and then taking log will have same effect but also it will remove ambiguity of log(0).</p></div> </div> </div> <div class="reply info"> <a class="comment-602546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602546"> <li> <div class="comment"> <table class="comment-table" commentId="602650" commentParentId="602546"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602650" href="?#comment-602650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602546" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602650"> <div class="moveup"> <div class="ttypography"><p>Thanks, got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-602650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602650"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603609" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaibhavsingh100070" style="position: relative;"> <img src='https://userpic.codeforces.org/792197/avatar/6a8b6f989cc93e7d.jpg'/> </a> <div><a href="/profile/vaibhavsingh100070" title="Pupil vaibhavsingh100070" class="rated-user user-green">vaibhavsingh100070</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 09:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603609" href="?#comment-603609" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603609" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="792197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603609"> <div class="moveup"> <div class="ttypography"><p>Can you please explain for this test case n = 5 a = [ 1, 2, 1, 4, 1] For this output is ** 2**. How in 2 steps we will make this array non decreasing?</p></div> </div> </div> <div class="reply info"> <a class="comment-603609 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603609 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603609"> <li> <div class="comment"> <table class="comment-table" commentId="604681" commentParentId="603609"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604681" href="?#comment-604681" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603609" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604681" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604681" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604681"> <div class="moveup"> <div class="ttypography"><p>Same doubt. Hoping someone to answer.</p><p>Edit: Got it. Should have read the question carefully. It says select any indices not continuous indices.</p><p>for n=5 ans array [ 1 2 1 4 1 ] </p><p>Step 1: Select indices : Select 3 and 5 ( begins from 0) Step 2: Increase by 1 then by 2 ( 2^x-1 , put x=1 and then 2) So array becomes : 1 2 4 4 4 which is non-decreasing.</p></div> </div> </div> <div class="reply info"> <a class="comment-604681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604681"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602409" href="?#comment-602409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602409" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602409"> <div class="moveup"> <div class="ttypography"><p>I have doubt in 1339 B -Sorted Adjacent Differences: If the array is: -2 5 5 6 The answer will be 5 -2 5 6 which is wrong Please explain if i am wrong</p></div> </div> </div> <div class="reply info"> <a class="comment-602409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602409"> <li> <div class="comment"> <table class="comment-table" commentId="602428" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602428" href="?#comment-602428" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602428"> <div class="moveup"> <div class="ttypography"><p>it is wrong because the required condition is not fulfilled as your answer will make seqeunce like this 7&lt;=7&gt;1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602428"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602433" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mestu" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mestu" title="Expert Mestu" class="rated-user user-blue">Mestu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602433" href="?#comment-602433" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602433" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="922247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602433"> <div class="moveup"> <div class="ttypography"><p>For array -2 5 5 6 the answer will be 5 5 -2 6 </p></div> </div> </div> <div class="reply info"> <a class="comment-602433 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602433 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602433"> <li> <div class="comment"> <table class="comment-table" commentId="602473" commentParentId="602433"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602473" href="?#comment-602473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602433" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602473"> <div class="moveup"> <div class="ttypography"><p>yes,but according to tutorial it is printing 5-2 5 6</p></div> </div> </div> <div class="reply info"> <a class="comment-602473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602473"> <li> <div class="comment"> <table class="comment-table" commentId="602740" commentParentId="602473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602740" href="?#comment-602740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602740"> <div class="moveup"> <div class="ttypography"><p>according to tutorial it will print 5 5 -2 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-602740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602740"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602427" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/inazuma_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/inazuma_11" title="Newbie inazuma_11" class="rated-user user-gray">inazuma_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602427" href="?#comment-602427" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602427" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1335781" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602427"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain O(N) approach for div 2C ? I know how to do it in O(NlogN) but not in O(N)</p></div> </div> </div> <div class="reply info"> <a class="comment-602427 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602427 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602427"> <li> <div class="comment"> <table class="comment-table" commentId="602432" commentParentId="602427"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602432" href="?#comment-602432" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602427" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602432" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602432"> <div class="moveup"> <div class="ttypography"><p>While traversing the array keep a count of what maximum difference have you seen so far from the previous element i.e maximum value uptil that i minus the array value at that i. Then once you found the maximum difference than going for finding the position of the highest bit in this maximum difference. The ans is going to be the value of this highest bit + 1. Make sure to include the edge case that if the maximum difference is 0 then the ans is also 0.</p></div> </div> </div> <div class="reply info"> <a class="comment-602432 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602432 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602432"> <li> <div class="comment"> <table class="comment-table" commentId="602492" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602492" href="?#comment-602492" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602492" 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="602492" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602492"> <div class="moveup"> <div class="ttypography"><p>Here is my thinking about this problem, which is much easier to understand: Lets say we need T seconds to make array becoming non descending. On each seconds from 1 to T we can choose any set of numbers from array to add 2^(t-1). It means that for each element of the array, on each second, we have choice to add or not to add this power of 2. So it means we can choose ANY number to add to each of array element. So the question is now simple: what is the min number M so that if for each a[i] we choose some number from 0 up to M to add to it, we can make array non descending. I just go from left to right, if next a[i+1] is less than a[i] I increase it to be equal a[i].</p></div> </div> </div> <div class="reply info"> <a class="comment-602492 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602492 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602492"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602531" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602531" href="?#comment-602531" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602531" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602531"> <div class="moveup"> <div class="ttypography"><p>why do we need to add the 1?</p></div> </div> </div> <div class="reply info"> <a class="comment-602531 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602531 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602531"> <li> <div class="comment"> <table class="comment-table" commentId="602549" commentParentId="602531"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602549" href="?#comment-602549" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602531" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602549" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602549"> <div class="moveup"> <div class="ttypography"><p>because suppose the highest bit is 2 that will be 100 but the time this would have occurred will be 3 seconds(1,2,4). Due to this, we need to add 1 to the highest bit that we obtain.</p></div> </div> </div> <div class="reply info"> <a class="comment-602549 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602549 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602549"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602429" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602429" href="?#comment-602429" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602429" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602429" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602429"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain how the answer of this testcase in problem div2/probC is 3.</p><p>4 2 -1 -3 -4</p></div> </div> </div> <div class="reply info"> <a class="comment-602429 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602429 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602429"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602431" href="?#comment-602431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602431" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602431"> <div class="moveup"> <div class="ttypography"><p>For DIV2D, first root the tree at any leaf (here, leaf = vertex with degree 1), and note that the XOR sum along any root leaf path must be 0. Now, delete all the leaves and the edges that lead from the leaves to their parents. In this graph, to get maximum value of f, assign distinct powers of 2 to each edge. Then re-introduce the leaves and leaf-to-parent edges, and assign them weights such that XOR sum from root to leaf will be zero. Notice that the values assigned to these leaf-to-parent edges will be distinct unless two leaves share the same parents. Thus, the maximum value of f will be n — 1 — (lvs — p), where lvs = number of leaves in this tree and p = number of nodes which have exactly one child leaf.</p><p>To get minimum f, do the same thing above (root tree at any leaf, then delete leaves and all leaf-parent edges). Then, in this new graph, assign weight 2 to the edge incident on the root, and to all other edges assign weight 1. Now, reintroduce the leaves and the leaf-parent edges, and assign these edges weights such that XOR sum along the root leaf path is 0. Notice that you will only have to assign weights of either 2 or 3 to these edges. So f &lt;= 3. The only case left is to work out when f = 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602431"> <li> <div class="comment"> <table class="comment-table" commentId="602644" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zass" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zass" title="Expert zass" class="rated-user user-blue">zass</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602644" href="?#comment-602644" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602644" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="916405" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602644"> <div class="moveup"> <div class="ttypography"><p>In lvs is root considered one of the leaves and in p is the parent of the root considered as one among p when the parent of root only has root as its child?</p></div> </div> </div> <div class="reply info"> <a class="comment-602644 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602644 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602644"> <li> <div class="comment"> <table class="comment-table" commentId="602811" commentParentId="602644"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602811" href="?#comment-602811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602644" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602811" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602811"> <div class="moveup"> <div class="ttypography"><p>In lvs, the root is not considered one of the leaves. And in p, parent of root is not included because root does not have a parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-602811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602811"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602798" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 18:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602798" href="?#comment-602798" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602798" class="CommentVoteFrame" data-commentRating="5" 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;">+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-602798"> <div class="moveup"> <div class="ttypography"><p>Nice explanation but I read your code to understand fully. =)) Code is still the best explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-602798 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602798 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602798"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="650339" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rmaa" style="position: relative;"> <img src='https://userpic.codeforces.org/499170/avatar/6e864314e460334e.jpg'/> </a> <div><a href="/profile/rmaa" title="Expert rmaa" class="rated-user user-blue">rmaa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2020 23:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-650339" href="?#comment-650339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="650339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="499170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-650339"> <div class="moveup"> <div class="ttypography"><p>Thanks so much, your explanation helped me understand this problem 2 months later! :) It's so mind-boggling to understand how one can come up with this construction in time during the contest.</p><p>The reason I want to post here is to add something to your solution in case anyone after me has the same question. (also to just solidify my own understanding) I actually had this question myself while reading — we know that the XOR from the root to all the different leaves must be zero. But how can one prove that the XOR from one leaf to another is also zero? (a path that does not include the root, but rather just two leaves in the tree?) After all we need to make EVERY path between leaves XOR to 0</p><p>The logic is quite simple. As we said before we know XOR of the paths from the root to the two leafs, call them L1 and L2, are both zero. These paths must share some similar segment (specifically its from the LCA(L1, L2) to the root). Call the XOR of this shared segment X. Then we know the XOR from the path from L1 to LCA(L1, L2) = X, and same with the path from L2 to LCA(L1, L2). Because if (x XOR y) = 0, then x = y, and the XOR of the whole path can be broken up the XOR of two segments L1 -&gt; LCA, LCA -&gt; root. (same with L2).</p><p>The editorial also explains this logic a bit but I hope what I wrote can help. </p></div> </div> </div> <div class="reply info"> <a class="comment-650339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-650339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-650339"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602484" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602484" href="?#comment-602484" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602484" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602484" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602484"> <div class="moveup"> <div class="ttypography"><p>I cant understand the editorial of Powered Addition clearly.Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-602484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602484"> <li> <div class="comment"> <table class="comment-table" commentId="602493" commentParentId="602484"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602493" href="?#comment-602493" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602493" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602493"> <div class="moveup"> <div class="ttypography"><p>I just post my 2 cents above, hope it is easier to understand</p></div> </div> </div> <div class="reply info"> <a class="comment-602493 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602493 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602493"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602629" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ZeroNik" style="position: relative;"> <img src='https://userpic.codeforces.org/1336702/avatar/4935627333ab6d15.jpg'/> </a> <div><a href="/profile/ZeroNik" title="Pupil ZeroNik" class="rated-user user-green">ZeroNik</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602629" href="?#comment-602629" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602629" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1336702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602629"> <div class="moveup"> <div class="ttypography"><p>Who can explain problem A again. I don't undersatand why answer is n</p></div> </div> </div> <div class="reply info"> <a class="comment-602629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602629"> <li> <div class="comment"> <table class="comment-table" commentId="602636" commentParentId="602629"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/invincibel31" style="position: relative;"> <img src='https://userpic.codeforces.org/842069/avatar/78296878ae951a3.jpg'/> </a> <div><a href="/profile/invincibel31" title="Expert invincibel31" class="rated-user user-blue">invincibel31</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602636" href="?#comment-602636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602629" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="842069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602636"> <div class="moveup"> <div class="ttypography"><p>ans is equal to n bcz of the vertically standing diamonds in each way there will be only one diamond which would be standing vertically and since the number of diamond in n hence and in n</p></div> </div> </div> <div class="reply info"> <a class="comment-602636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602636"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602791" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hasnaine_" style="position: relative;"> <img src='https://userpic.codeforces.org/553185/avatar/dbae027ec9304551.jpg'/> </a> <div><a href="/profile/Hasnaine_" title="Expert Hasnaine_" class="rated-user user-blue">Hasnaine_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602791" href="?#comment-602791" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602791" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="553185" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602791"> <div class="moveup"> <div class="ttypography"><p><strong>Problem Div1(C), Div2(E):</strong> </p><p>Can anyone please elaborate on why this combination on bitmasking works?</p><p>Or, how to prove this combination works?</p><p>Thanks in advance. </p></div> </div> </div> <div class="reply info"> <a class="comment-602791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602791"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RedSnowstorm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RedSnowstorm" title="Expert RedSnowstorm" class="rated-user user-blue">RedSnowstorm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602796" href="?#comment-602796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602796" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="789793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602796"> <div class="moveup"> <div class="ttypography"><p>Could someone please elaborate a bit more on Div1 C ? I understand the solution up to the first picture, but I don't understand neither the meaning of the second picture nor the rest of the solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602796"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602873" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ateev_mishra7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ateev_mishra7" title="Pupil ateev_mishra7" class="rated-user user-green">ateev_mishra7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602873" href="?#comment-602873" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602873" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174913" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602873"> <div class="moveup"> <div class="ttypography"><p>Why does my solution to Div2-C is not working . <a href="https://codeforces.com/contest/1339/submission/76407068">https://codeforces.com/contest/1339/submission/76407068</a></p><p>can somebody please help me out on this .</p></div> </div> </div> <div class="reply info"> <a class="comment-602873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602873"> <li> <div class="comment"> <table class="comment-table" commentId="603718" commentParentId="602873"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603718" href="?#comment-603718" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603718" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603718" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603718"> <div class="moveup"> <div class="ttypography"><p>Well let's take the sequence as 1 4 1 4, your code outputs 3 while it is supposed to output 2 since you can add 1 and 2 to the third element and get a sorted output.</p></div> </div> </div> <div class="reply info"> <a class="comment-603718 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603718 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603718"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="603291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vyush" style="position: relative;"> <img src='https://userpic.codeforces.org/814106/avatar/d2c40519525d0732.jpg'/> </a> <div><a href="/profile/Vyush" title="Expert Vyush" class="rated-user user-blue">Vyush</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603291" href="?#comment-603291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603291" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603291" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603291"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain division1C/division2E I am not able to understand the approach in the editorial.I got the nim product observation but I don't know how to implement it also i don't get the editorials approach.If anyone could help that would be great.Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-603291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604316" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sheaf" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sheaf" title="Expert sheaf" class="rated-user user-blue">sheaf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 19:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604316" href="?#comment-604316" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604316" 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="604316" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="509827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604316"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, as for Div1E, isn't $$$R=in(P)\cap Q$$$, instead it is $$$R=in(V)\cap Q$$$? The latter just doesn't make sense if you consider the lemma 3. $$$in(V)$$$ is the subset of all vertices that have at least one outgoing edge, $$$in(P)\cap Q$$$ is the subset of all vertices of $$$Q$$$ that have at least one outgoing edge. Then lemma 3, which says there are edges from set $$$S$$$ to $$$R$$$, can't be true because it says that $$$S$$$ — a subset of $$$Q$$$ without outgoing edges — has edges pointing to $$$R$$$. On contrary, if we set $$$R=in(P)\cap Q$$$ we, can prove lemma 3 by forbidding the configuration from the statement. Also, can't really prove part of lemma 4 that says that $$$R$$$ has no cycles without it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604316 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604316 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604316"> <li> <div class="comment"> <table class="comment-table" commentId="604403" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604403" href="?#comment-604403" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604403" 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="604403" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604403"> <div class="moveup"> <div class="ttypography"><p>(erased)</p></div> </div> </div> <div class="reply info"> <a class="comment-604403 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604403 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604403"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604580" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 01:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604580" href="?#comment-604580" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604580" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604580" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604580"> <div class="moveup"> <div class="ttypography"><p>oops, sorry, I understood your comment wrong. To be honest, I don't fully understand approach of this problem, so I would like to call author of this problem directly. <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></p></div> </div> </div> <div class="reply info"> <a class="comment-604580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604580"> <li> <div class="comment"> <table class="comment-table" commentId="604593" commentParentId="604580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604593" href="?#comment-604593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604593" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604593"> <div class="moveup"> <div class="ttypography"><p>Ugh, bad boy. You should be more responsible to your round.</p></div> </div> </div> <div class="reply info"> <a class="comment-604593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604593"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604591" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604591" href="?#comment-604591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604591" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604591"> <div class="moveup"> <div class="ttypography"><p>Oh, I didn't realise that I used the variable $$$V$$$ 2 times. Now I fixed it. When I said $$$in(V) \cap Q$$$ I refered to the $$$V$$$ in Lemma 2. Thanks for pointinh out my mistake.</p></div> </div> </div> <div class="reply info"> <a class="comment-604591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604591"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604631" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 07:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604631" href="?#comment-604631" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604631"> <div class="moveup"> <div class="ttypography"><p>Hi, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, how does observation 1 of edge weight problem work since the shape of tree is determined by input rather than can be arbitrary constructed as in observation 1? Take example input 3 for instance. Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-604631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604631"> <li> <div class="comment"> <table class="comment-table" commentId="604757" commentParentId="604631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604757" href="?#comment-604757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604757" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604757"> <div class="moveup"> <div class="ttypography"><p><img alt="ex1" src="/predownloaded/a2/a8/a2a877e5c47802fc77cb6bee8965a15f80b6e799.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You can see that we can make $$$f = 1$$$ in this tree anyway.</p></div> </div> </div> <div class="reply info"> <a class="comment-604757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604757"> <li> <div class="comment"> <table class="comment-table" commentId="605625" commentParentId="604757"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605625" href="?#comment-605625" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604757" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605625" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605625"> <div class="moveup"> <div class="ttypography"><p>I must misunderstand your meaning, but doesn't f=2 in the graph since there are weight of 1 and 2?</p><p>Or do you mean that the edge on 7-4-3 could be equivalent to a single edge with weight of 3=weight(7,4) xor weight(4,3)=2 xor 1? Thus in this way the observation 1 can be applied?</p></div> </div> </div> <div class="reply info"> <a class="comment-605625 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605625 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605625"> <li> <div class="comment"> <table class="comment-table" commentId="605631" commentParentId="605625"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605631" href="?#comment-605631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605625" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605631"> <div class="moveup"> <div class="ttypography"><p>This picture shows how you can manage $$$f \le 3$$$ in this tree with first observation. By &quot; <em>You can see that we can make $$$f = 1$$$ in this tree any</em> &quot; I mean you can replace all weights $$$2$$$ to $$$1$$$ to make $$$f = 1$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-605631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605631"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/karanbhatia116" style="position: relative;"> <img src='https://userpic.codeforces.org/872128/avatar/afb324a25af3a491.jpg'/> </a> <div><a href="/profile/karanbhatia116" title="Newbie karanbhatia116" class="rated-user user-gray">karanbhatia116</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604739" href="?#comment-604739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872128" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604739"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain me the second test case for Div1A/Div2C(<a href="/contest/1338/problem/A" title="Codeforces Round 633 (Div. 1)">1338A - Powered Addition</a>)?</p> <pre><code>Input: 6 3 1000000000 0 -1000000000 1 6 2 -1000000000 1000000000 2 1000000000 -1000000000 2 1000000000 1000000000 2 -1000000000 -1000000000 Output: 31 0 0 31 0 0 </code></pre><p>How is the output 31 and not 32? If it is 31 then we must have added 2^30 in 0 and -1000000000 but that does not make the array non-decreasing in the first test case.</p></div> </div> </div> <div class="reply info"> <a class="comment-604739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604739"> <li> <div class="comment"> <table class="comment-table" commentId="604760" commentParentId="604739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 12:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604760" href="?#comment-604760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604760" 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="604760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604760"> <div class="moveup"> <div class="ttypography"><p>Select $$$2$$$-nd index at last second only, and $$$3$$$-rd index all the time. Then you get </p><p>$$$a = [10^{9}, 0, -10^{9}] \to [10^{9}, 0 + 2^{30}, -10^{9} + 2^{0} + 2^{1} + \ldots + 2^{30}] = [1000000000, 1073741824, 1147483647]$$$</p><p>So you can make $$$a$$$ non-decreasing in $$$31$$$ seconds.</p></div> </div> </div> <div class="reply info"> <a class="comment-604760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604760"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605553" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 09:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605553" href="?#comment-605553" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605553" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605553"> <div class="moveup"> <div class="ttypography"><p>why does the answer for div2-C depends only on largest difference? Can someone explain in detailed manner i am unable to get the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-605553 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605553 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605553"> <li> <div class="comment"> <table class="comment-table" commentId="605637" commentParentId="605553"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605637" href="?#comment-605637" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605553" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605637" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605637" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605637"> <div class="moveup"> <div class="ttypography"><p>Fact 1: $$$2^{0} + 2^{1} + \ldots + 2^{t-1} \lt 2^{t}$$$.</p><p>This means if you want to add something equal or bigger than $$$2^{t}$$$ on some position, then you should use more than $$$t$$$ seconds.</p><p>Fact 2: Required seconds is determined by maximum bit of difference.</p><p>From two facts you can observe that smaller difference leads to shorter time.</p><p>I will write few examples below;</p> <ul> <li>diff = 0 -&gt; 0 second</li> <li>diff = 1 -&gt; 1 second ($$$1 = 2^{0}$$$)</li> <li>diff = 2 -&gt; 2 seconds ($$$2 = 2^{1}$$$)</li> <li>diff = 3 -&gt; 2 seconds ($$$3 = 2^{0} + 2^{1}$$$)</li> <li>diff = 4 -&gt; 3 seconds ($$$4 = 2^{2}$$$)</li> <li>diff = 5 -&gt; 3 seconds ($$$5 = 2^{0} + 2^{2}$$$)</li> <li>diff = 6 -&gt; 3 seconds ($$$6 = 2^{1} + 2^{2}$$$)</li> <li>diff = 7 -&gt; 3 seconds ($$$7 = 2^{0} + 2^{1} + 2^{2}$$$)</li> <li>...</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-605637 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605637 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605637"> <li> <div class="comment"> <table class="comment-table" commentId="605676" commentParentId="605637"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 12:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605676" href="?#comment-605676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605637" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605676"> <div class="moveup"> <div class="ttypography"><p>Thank you for your explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-605676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605676"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605607" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anshul23" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anshul23" title="Expert anshul23" class="rated-user user-blue">anshul23</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 10:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605607" href="?#comment-605607" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605607" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="551535" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-605607"> <div class="moveup"> <div class="ttypography"><p>Nice editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-605607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605607"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grapo_Oranges" style="position: relative;"> <img src='https://userpic.codeforces.org/1443313/avatar/3242fe30f43d5e9f.jpg'/> </a> <div><a href="/profile/grapo_Oranges" title="Expert grapo_Oranges" class="rated-user user-blue">grapo_Oranges</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 13:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605691" href="?#comment-605691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605691" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605691"> <div class="moveup"> <div class="ttypography"><p>@Anyone who solved Div2. D during the contest, can you explain how did you actually figure out the solution and was there any specific problem you ever did in past that helped you to solve this problem?</p></div> </div> </div> <div class="reply info"> <a class="comment-605691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606212" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ankit_12" style="position: relative;"> <img src='https://userpic.codeforces.org/1461518/avatar/2c0c3df83d1920d2.jpg'/> </a> <div><a href="/profile/Ankit_12" title="Pupil Ankit_12" class="rated-user user-green">Ankit_12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 10:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606212" href="?#comment-606212" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="606212" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="606212" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1461518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606212"> <div class="moveup"> <div class="ttypography"><p>Why this sequence is not correct for n=9, A/C to question Perfect Triples please Any one Help???</p><p>9 : 1 2 3 4 3 7 8 4 12</p></div> </div> </div> <div class="reply info"> <a class="comment-606212 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606212 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606212"> <li> <div class="comment"> <table class="comment-table" commentId="606260" commentParentId="606212"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 13:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606260" href="?#comment-606260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606212" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606260"> <div class="moveup"> <div class="ttypography"><p>Because $$$3$$$ is used twice in your sequence.</p></div> </div> </div> <div class="reply info"> <a class="comment-606260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606260"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606777" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/striver_79" style="position: relative;"> <img src='https://userpic.codeforces.org/584222/avatar/92d0d608686eabcc.jpg'/> </a> <div><a href="/profile/striver_79" title="Candidate Master striver_79" class="rated-user user-violet">striver_79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 13:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606777" href="?#comment-606777" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606777" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="584222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606777"> <div class="moveup"> <div class="ttypography"><p>Video editorial for <a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div2D</a>/<a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div1B</a>: </p></div> </div> </div> <div class="reply info"> <a class="comment-606777 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606777 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606777"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607351" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/richikchanda1999" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/richikchanda1999" title="Pupil richikchanda1999" class="rated-user user-green">richikchanda1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 18:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607351" href="?#comment-607351" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607351" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="510979" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607351"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces,</p><p>Can anyone help me to come up with a better approach to the excluded problem (<a href="https://codeforces.com/gym/276159/problem/D1A_old">https://codeforces.com/gym/276159/problem/D1A_old</a>) apart from the brute-force approach which is giving TLE?</p></div> </div> </div> <div class="reply info"> <a class="comment-607351 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607351 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607351"> <li> <div class="comment"> <table class="comment-table" commentId="608851" commentParentId="607351"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/22/2020 18:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-608851" href="?#comment-608851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607351" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="608851" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="608851" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-608851"> <div class="moveup"> <div class="ttypography"><p>$$$x \oplus (x \cdot 2^{30}) = x \cdot (1 + 2^{30})$$$ if $$$x &lt; 2^{30}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-608851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-608851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-608851"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="619618" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/10/2020 21:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-619618" href="?#comment-619618" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="619618" 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="619618" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-619618"> <div class="moveup"> <div class="ttypography"><p>After a few weeks when I want to solve the problems I just realized the Editorial is so beautiful, those well-illustrated pictures and interesting stories made the Editorial so great!</p><p>But I had problems solving D1E. I cannot figure out why the <strong>Lemma 3</strong> and <strong>Lemma 6a/b</strong> are correct (And of course the final observations). Can you give proofs for them?</p><p><strong>UPD: After asking others, now I understood. Anyway, thanks the great Editorial!</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-619618 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-619618 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-619618"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="620074" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/11/2020 17:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620074" href="?#comment-620074" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="620074" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620074"> <div class="moveup"> <div class="ttypography"><p>i found a crazy solution of div1B <a href="https://codeforces.com/contest/1338/submission/76346806">https://codeforces.com/contest/1338/submission/76346806</a> can anyone plz explain the logic</p></div> </div> </div> <div class="reply info"> <a class="comment-620074 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620074 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620074"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="630800" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shpvb" style="position: relative;"> <img src='https://userpic.codeforces.org/720608/avatar/3fa49fe2fc134d7b.jpg'/> </a> <div><a href="/profile/shpvb" title="Candidate Master shpvb" class="rated-user user-violet">shpvb</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/27/2020 13:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-630800" href="?#comment-630800" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="630800" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-630800"> <div class="moveup"> <div class="ttypography"><p>Can someone provide insight into the mathematical induction referred to in observation 2 of div1C (Perfect Triples)?</p></div> </div> </div> <div class="reply info"> <a class="comment-630800 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-630800 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-630800"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="792521" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Livu_sz" style="position: relative;"> <img src='https://userpic.codeforces.org/1922428/avatar/3153d345afda896c.jpg'/> </a> <div><a href="/profile/Livu_sz" title="Expert Livu_sz" class="rated-user user-blue">Livu_sz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/19/2021 06:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-792521" href="?#comment-792521" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="792521" 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="792521" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1922428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-792521"> <div class="moveup"> <div class="ttypography"><p>B was tough</p></div> </div> </div> <div class="reply info"> <a class="comment-792521 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-792521 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-792521"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1064206" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sartq" style="position: relative;"> <img src='https://userpic.codeforces.org/3093050/avatar/ec7dcd19bb83efab.jpg'/> </a> <div><a href="/profile/sartq" title="Newbie sartq" class="rated-user user-gray">sartq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2023 06:30">5 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1064206" href="?#comment-1064206" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1064206" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="3093050" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1064206"> <div class="moveup"> <div class="ttypography"><p>In div2B can we solve the problem using a hashMap, like storing the values of differences of array and their indexes?</p></div> </div> </div> <div class="reply info"> <a class="comment-1064206 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1064206 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1064206"> </ul> </div> <br/> <div id="editBox-82006" 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 firstPreview82006 = true; var lastPreviewContent82006 = ''; 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=82006] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=82006] 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-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, 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:28:37</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:'81288c53eb1e161c',t:'MTY5NjcwNjkxNy4zNTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1338C
1338
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$$$ натуральных чисел, построенную повторением следующих шагов:</p><ol> <li> Найдите лексикографически наименьшую тройку натуральных чисел $$$(a, b, c)$$$ такую, ​​что <ul> <li> $$$a \oplus b \oplus c = 0$$$, где $$$\oplus$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Битовая_операция#Исключающее_ИЛИ">побитовое исключающее ИЛИ</a>. </li><li> $$$a$$$, $$$b$$$, $$$c$$$ не находятся в $$$s$$$. </li></ul> Здесь тройка целых чисел $$$(a_1, b_1, c_1)$$$ считается лексикографически меньше тройки $$$(a_2, b_2, c_2)$$$, если последовательность $$$[a_1, b_1, c_1]$$$ лексикографически меньше последовательности $$$[a_2, b_2, c_2]$$$ </li><li> Добавьте $$$a$$$, $$$b$$$, $$$c$$$ в конец $$$s$$$ в этом порядке. </li><li> Вернитесь к первому шагу. </li></ol><p>У вас есть целое число $$$n$$$. Найдите $$$n$$$-й элемент $$$s$$$.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p><p>Последовательность $$$a$$$ лексикографически меньше последовательности $$$b$$$, если в первой позиции, где $$$a$$$ и $$$b$$$ различны, в последовательности $$$a$$$ элемент меньше, чем соответствующий элемент в $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$)  — количество тестовых случаев.</p><p>Каждая из следующих $$$t$$$ строк содержит одно целое число $$$n$$$ ($$$1\le n \le 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> 9 1 2 3 4 5 6 7 8 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 4 8 12 5 10 15 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые несколько элементов $$$s$$$ это $$$1, 2, 3, 4, 8, 12, 5, 10, 15, \dots $$$</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="56346962ab420a717410f68239261298"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="5c85cbb657e064c2cfa3c38de5074b5925e3ec82"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='56346962ab420a717410f68239261298'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1338%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='56346962ab420a717410f68239261298'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1338">Codeforces Round 633 (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='56346962ab420a717410f68239261298'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1338/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй"> разделяй и властвуй </span> </div> <div class="roundbox borderTopRound 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='56346962ab420a717410f68239261298'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590533"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='56346962ab420a717410f68239261298'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590533"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10753" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10760" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1338">Задачи</a></li> <li><a href="/contest/1338/submit">Отослать</a></li> <li><a href="/contest/1338/my">Мои посылки</a></li> <li><a href="/contest/1338/status">Статус</a></li> <li><a href="/contest/1338/hacks">Взломы</a></li> <li><a href="/contest/1338/room/1">Комната</a></li> <li><a href="/contest/1338/standings">Положение</a></li> <li><a href="/contest/1338/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_fa608c2ad79892fd7df6b0a8fd90bc3ef6635b57"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ натуральных чисел, построенную повторением следующих шагов:</p><ol> <li> Найдите лексикографически наименьшую тройку натуральных чисел $$$(a, b, c)$$$ такую, ​​что <ul> <li> $$$a \oplus b \oplus c = 0$$$, где $$$\oplus$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Битовая_операция#Исключающее_ИЛИ">побитовое исключающее ИЛИ</a>. </li><li> $$$a$$$, $$$b$$$, $$$c$$$ не находятся в $$$s$$$. </li></ul> Здесь тройка целых чисел $$$(a_1, b_1, c_1)$$$ считается лексикографически меньше тройки $$$(a_2, b_2, c_2)$$$, если последовательность $$$[a_1, b_1, c_1]$$$ лексикографически меньше последовательности $$$[a_2, b_2, c_2]$$$ </li><li> Добавьте $$$a$$$, $$$b$$$, $$$c$$$ в конец $$$s$$$ в этом порядке. </li><li> Вернитесь к первому шагу. </li></ol><p>У вас есть целое число $$$n$$$. Найдите $$$n$$$-й элемент $$$s$$$.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p><p>Последовательность $$$a$$$ лексикографически меньше последовательности $$$b$$$, если в первой позиции, где $$$a$$$ и $$$b$$$ различны, в последовательности $$$a$$$ элемент меньше, чем соответствующий элемент в $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$)  — количество тестовых случаев.</p><p>Каждая из следующих $$$t$$$ строк содержит одно целое число $$$n$$$ ($$$1\le n \le 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> 9 1 2 3 4 5 6 7 8 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 4 8 12 5 10 15 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые несколько элементов $$$s$$$ это $$$1, 2, 3, 4, 8, 12, 5, 10, 15, \dots $$$</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/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:36</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249dfc1a351628',t:'MTY5NjY2NTY5Ni45MzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u041a\u043e\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\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\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\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "*2200"]
https://codeforces.com/blog/entry/75913
<!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="8bc765f3680682fd8f2decef62cad97d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Codeforces Round #633 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #633 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='8bc765f3680682fd8f2decef62cad97d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F75913">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='8bc765f3680682fd8f2decef62cad97d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:36:25</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:36:25</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='8bc765f3680682fd8f2decef62cad97d'/> <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/McDic">McDic</a></li> <li class="current selectedLava"><a href="/blog/McDic">Blog</a></li> <li><a href="/teams/with/McDic">Teams</a></li> <li><a href="/submissions/McDic">Submissions</a></li> <li><a href="/groups/with/McDic">Groups</a></li> <li><a href="/contests/with/McDic">Contests</a></li> <li><a href="/contests/writer/McDic">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/McDic" style="text-decoration:none;color:black !important;">McDic's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="76444"> <div class="title"> <a href="/blog/entry/75913"> <p>Codeforces Round #633 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a>, <a href="/topic/76444/en2">history</a>, <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p>Hello! I hope all of you enjoyed my contest!</p> <div class="problemTutorial" problemcode="1339A">Tutorial is loading...</div><p><strong>Behind story of A</strong>:</p> <ul> <li>I tried to make the easiest Div2A ever. Will it work? :)</li> </ul> <div class="problemTutorial" problemcode="1339B">Tutorial is loading...</div><p><strong>Behind story of B</strong>:</p> <ul> <li>I tried to block various heuristics. There were some critical heuristics which could pass so many cases. Fortunately I blocked them during testing period, so I hope there won't be much FST this time.</li> </ul> <div class="problemTutorial" problemcode="1338A">Tutorial is loading...</div><p><strong>Behind story of D2C/D1A</strong>:</p> <ul> <li>Originally, there was a different problem for this position. But it used XOR. As I made new D2E/D1C problem, I threw old D2C/D1A away and put this.</li> </ul> <div class="problemTutorial" problemcode="1338B">Tutorial is loading...</div><p><strong>Behind story of D2D/D1B</strong>:</p> <ul> <li>This problem is the most popular problem among testers. I also like this problem a lot.</li> </ul> <div class="problemTutorial" problemcode="1338C">Tutorial is loading...</div><p><strong>Behind story of D2E/D1C</strong>:</p> <ul> <li>Feedback for this problem was too different by testers.</li> <li>I made this problem by modifying <a href="https://codeforces.com/contest/1242/problem/D">Number Discovery</a>, which is one of my previous problems.</li> <li>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this.</li> </ul> <div class="problemTutorial" problemcode="1338D">Tutorial is loading...</div><p><strong>Behind story of D1D</strong>:</p> <ul> <li>This problem was supposed to be D2E at first. But all LGM testers failed this problem during VC, so we thought that this problem's difficulty is high. Meanwhile, I found that old D1D problem can be easily googled, so we removed that problem, push this problem to be D1D, and made another D1C problem. I will share old D1D later.</li> </ul> <div class="problemTutorial" problemcode="1338E">Tutorial is loading...</div><p><strong>Behind story of D1E</strong>:</p> <ul> <li>Thanks <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a> for writing this problem. She is genius in both singing and problemsolving.</li> </ul></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/1338" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 1)</a> </span> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1339" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-88959-76444").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "88959", blogEntryId: "75913", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=mcdic" class="tag notice" style="text-decoration: none;">mcdic</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-76444"><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'>+346</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-76444"><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/McDic"><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/McDic"> McDic </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/75913#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/75913#comments"> 225 </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="82006"> <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 (171)</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="601867" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stefdasca" style="position: relative;"> <img src='https://userpic.codeforces.org/492453/avatar/429fc64e07ff3f4.jpg'/> </a> <div><a href="/profile/stefdasca" title="Candidate Master stefdasca" class="rated-user user-violet">stefdasca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601867" href="?#comment-601867" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601867" 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="601867" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="492453" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601867"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=crOSe84Q6HQ">Video tutorial for div1A/div2C</a></p><p><a href="https://www.youtube.com/watch?v=MMtnJDMM3IE">Video tutorial for div1B/div2D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-601867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601867"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601870" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kerO_o" style="position: relative;"> <img src='https://userpic.codeforces.org/406813/avatar/a505f416e75a37bd.jpg'/> </a> <div><a href="/profile/kerO_o" title="Master kerO_o" class="rated-user user-orange">kerO_o</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601870" href="?#comment-601870" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601870" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="406813" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601870"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-601870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601870"> <li> <div class="comment"> <table class="comment-table" commentId="601963" commentParentId="601870"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601963" href="?#comment-601963" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601963" class="CommentVoteFrame" data-commentRating="30" 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:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601963"> <div class="moveup"> <div class="ttypography"><p>what does this &quot;orz&quot; mean? </p></div> </div> </div> <div class="reply info"> <a class="comment-601963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601963"> <li> <div class="comment"> <table class="comment-table" commentId="602114" commentParentId="601963"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yash18" style="position: relative;"> <img src='https://userpic.codeforces.org/858176/avatar/3cdce86e6de339b8.jpg'/> </a> <div><a href="/profile/yash18" title="Pupil yash18" class="rated-user user-green">yash18</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602114" href="?#comment-602114" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602114" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602114" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="858176" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602114"> <div class="moveup"> <div class="ttypography"><p>Bow down! Bow down to the <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602114 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602114 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602114"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601879" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SkySurfer" style="position: relative;"> <img src='https://userpic.codeforces.org/684272/avatar/41e617735365cc0e.jpg'/> </a> <div><a href="/profile/SkySurfer" title="Specialist SkySurfer" class="rated-user user-cyan">SkySurfer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601879" href="?#comment-601879" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601879" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="684272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601879"> <div class="moveup"> <div class="ttypography"><p>Best Editorial Ever ....Nice Explanation Of both Problems and Solutions . </p></div> </div> </div> <div class="reply info"> <a class="comment-601879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601879"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601890" href="?#comment-601890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601890" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601890" class="CommentVoteFrame" data-commentRating="32" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+32</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601890"> <div class="moveup"> <div class="ttypography"><p>For Div1C, I found out that the nth tuple (an, bn, cn) is basically this: (found via OEIS)</p> <ol> <li><p>an -&gt; nth number with odd number of bits</p></li> <li><p>bn -&gt; nim_multiplcation(2, an) (<a href="https://oeis.org/A006015">https://oeis.org/A006015</a>)</p></li> <li><p>cn = an ^ bn.</p></li> </ol><p>But I was still not able to solve the problem because I didn't know nim multiplication nor did I find any implementation over the net.</p></div> </div> </div> <div class="reply info"> <a class="comment-601890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601890"> <li> <div class="comment"> <table class="comment-table" commentId="601914" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601914" href="?#comment-601914" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601914" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601914"> <div class="moveup"> <div class="ttypography"><p>Nim Arithmetic is definitely overkill for this problem. </p></div> </div> </div> <div class="reply info"> <a class="comment-601914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601914"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="601919" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601919" href="?#comment-601919" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601919" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601919" class="CommentVoteFrame" data-commentRating="71" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+71</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601919"> <div class="moveup"> <div class="ttypography"><p>We found that during testing and thought it wasn't much of an issue exactly because of that, probably you'd spend more time searching about nim multiplication than if you just solved the problem lol</p></div> </div> </div> <div class="reply info"> <a class="comment-601919 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601919 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601919"> <li> <div class="comment"> <table class="comment-table" commentId="601942" commentParentId="601919"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601942" href="?#comment-601942" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601919" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601942" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601942"> <div class="moveup"> <div class="ttypography"><p>Yeah, that is what happened ... I kept on searching for nim multiplcation here and there and wasted too much time. I should have come up with some other approaches ... </p></div> </div> </div> <div class="reply info"> <a class="comment-601942 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601942 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601942"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602731" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602731" href="?#comment-602731" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602731" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602731"> <div class="moveup"> <div class="ttypography"><p>A solution with nim multiplcation: <a href="/contest/1338/submission/76499145" title="Submission 76499145 by amane-ame">76499145</a></p><p>There is no doubt that it is much more complicated than the general solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602731 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602731 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602731"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601893" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Endagorion" style="position: relative;"> <img src='https://userpic.codeforces.org/1643/avatar/5c0b493cf8428ab6.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Endagorion" title="International Grandmaster Endagorion" class="rated-user user-red">Endagorion</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601893" href="?#comment-601893" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601893" class="CommentVoteFrame" data-commentRating="192" data-commentUserId="1643" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+192</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601893"> <div class="moveup"> <div class="ttypography"><p>I don't have proof, but in div1C any triple appears to be $$$(x, x \otimes 2, x \otimes 3)$$$, where $$$\otimes$$$ is nim multiplication.</p></div> </div> </div> <div class="reply info"> <a class="comment-601893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601893"> <li> <div class="comment"> <table class="comment-table" commentId="601983" commentParentId="601893"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601983" href="?#comment-601983" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601983" class="CommentVoteFrame" data-commentRating="64" 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;">+64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601983"> <div class="moveup"> <div class="ttypography"><p>:o</p></div> </div> </div> <div class="reply info"> <a class="comment-601983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601983"> <li> <div class="comment"> <table class="comment-table" commentId="602418" commentParentId="601983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jerry__Jiang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jerry__Jiang" title="Master Jerry__Jiang" class="rated-user user-orange">Jerry__Jiang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602418" href="?#comment-602418" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601983" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602418" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1198521" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602418"> <div class="moveup"> <div class="ttypography"><p>:)</p></div> </div> </div> <div class="reply info"> <a class="comment-602418 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602418 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602418"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601939" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601939" href="?#comment-601939" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601939" 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="601939" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-41" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601939"> <div class="moveup"> <div class="ttypography"><p>[DELETED]</p></div> </div> </div> <div class="reply info"> <a class="comment-601939 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601939 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601939"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prodelta" style="position: relative;"> <img src='https://userpic.codeforces.org/847522/avatar/e144f36263828062.jpg'/> </a> <div><a href="/profile/prodelta" title="Pupil prodelta" class="rated-user user-green">prodelta</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601950" href="?#comment-601950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601950" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="847522" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601950"> <div class="moveup"> <div class="ttypography"><p>System testing is finished , Editorials are out , but my submission for Problem — A still shows Pretests Passed . Link : <a href="https://codeforces.com/contest/1339/submission/76340409">Here</a></p><p>Have I committed some fatal sin for which I am being given such a brutal punishment ?</p><p>What should I do now ?</p></div> </div> </div> <div class="reply info"> <a class="comment-601950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601950"> <li> <div class="comment"> <table class="comment-table" commentId="601964" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shubhammitt" style="position: relative;"> <img src='https://userpic.codeforces.org/785906/avatar/ecb76ca8bc2663f4.jpg'/> </a> <div><a href="/profile/shubhammitt" title="Expert shubhammitt" class="rated-user user-blue">shubhammitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601964" href="?#comment-601964" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601964" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="785906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601964"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-601964 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601964 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601964"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602003" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602003" href="?#comment-602003" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602003" 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-602003"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-602003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602003"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602451" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chidoring" style="position: relative;"> <img src='https://userpic.codeforces.org/1455809/avatar/d62042cde12a7b4e.jpg'/> </a> <div><a href="/profile/chidoring" title="Pupil chidoring" class="rated-user user-green">chidoring</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602451" href="?#comment-602451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602451" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1455809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602451"> <div class="moveup"> <div class="ttypography"><p>rip</p></div> </div> </div> <div class="reply info"> <a class="comment-602451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602451"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601953" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_DynamicCube" style="position: relative;"> <img src='https://userpic.codeforces.org/1381092/avatar/ca9726e93700302b.jpg'/> </a> <div><a href="/profile/_DynamicCube" title="Pupil _DynamicCube" class="rated-user user-green">_DynamicCube</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601953" href="?#comment-601953" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601953" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1381092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601953"> <div class="moveup"> <div class="ttypography"><p>재밌는 문제들 감사합니다! (Thank you for the interesting questions!)</p></div> </div> </div> <div class="reply info"> <a class="comment-601953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601953"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601956" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AceKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AceKing" title="Candidate Master AceKing" class="rated-user user-violet">AceKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601956" href="?#comment-601956" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601956" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="910788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601956"> <div class="moveup"> <div class="ttypography"><p>Fastest editorial I have ever seen!</p></div> </div> </div> <div class="reply info"> <a class="comment-601956 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601956 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601956"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601960" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601960" href="?#comment-601960" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601960" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601960" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601960"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces, I don't have any idea how to approach problems like Div2.D/Div1.B, can someone give me an advice? I am not sure what should I learn first in order to be able to come with a solution to this problem. Thanks :)</p></div> </div> </div> <div class="reply info"> <a class="comment-601960 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601960 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601960"> <li> <div class="comment"> <table class="comment-table" commentId="602364" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 06:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602364" href="?#comment-602364" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602364" class="CommentVoteFrame" data-commentRating="3" 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: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-602364"> <div class="moveup"> <div class="ttypography"><p>From my experience, Div 2 D tends to vary quite bit. I think the best way to go about it is to just keep on practicing a bunch of div 2 D, and look at editorials if you don't quite understand. Also, nice profile picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602364"> <li> <div class="comment"> <table class="comment-table" commentId="602461" commentParentId="602364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602461" href="?#comment-602461" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602364" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602461" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602461" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602461"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, I will keep practicing then :D. PS: I also like your picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602461 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602461 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602461"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602499" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602499" href="?#comment-602499" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602499" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602499"> <div class="moveup"> <div class="ttypography"><p>Well from my experience, it appears atleast one of C/D almost always involves graphs and/or DP. I'd recommend first learning all about graphs, especially some important techniques like DFS, BFS, multi-source BFS, SCC, bridges, cut-vertices etc.[Graphs are really awesome :] Then later move on to DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-602499 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602499 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602499"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604120" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 16:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604120" href="?#comment-604120" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604120" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604120"> <div class="moveup"> <div class="ttypography"><p>IMO you should first learn a little advanced algorithms and data structures and etc., also solve-up contests and past ones, i say the best way is to take virtual contests and then solve the rest of the problems excluding the cases you full the contest :). Also solve Div2.E after the contests, it's fine if you cant solve them, just take your time and try your best then go to editorial and make sure you fully understand the editorial and the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604120"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601962" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601962" href="?#comment-601962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601962" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-118" 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;">-118</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601962"> <div class="moveup"> <div class="ttypography"><p>i think it is better to provide codes instead of stories</p></div> </div> </div> <div class="reply info"> <a class="comment-601962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601962"> <li> <div class="comment"> <table class="comment-table" commentId="601995" commentParentId="601962"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601995" href="?#comment-601995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601995" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601995"> <div class="moveup"> <div class="ttypography"><p>That's why the button showing number of solves next to a problem exists. Click on that and you can see many codes and sort by speed, code length, etc.</p></div> </div> </div> <div class="reply info"> <a class="comment-601995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601995"> <li> <div class="comment"> <table class="comment-table" commentId="601999" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601999" href="?#comment-601999" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601999" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-30" 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;">-30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601999"> <div class="moveup"> <div class="ttypography"><p>I know that, But I want to see the code of the explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-601999 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601999 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601999"> <li> <div class="comment"> <table class="comment-table" commentId="602002" commentParentId="601999"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602002" href="?#comment-602002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601999" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602002" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602002"> <div class="moveup"> <div class="ttypography"><p>Wtf does that mean. Every code is most likely some variation of the explanation if it passed...</p></div> </div> </div> <div class="reply info"> <a class="comment-602002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602002"> <li> <div class="comment"> <table class="comment-table" commentId="602006" commentParentId="602002"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602006" href="?#comment-602006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602002" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602006" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-55" 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;">-55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602006"> <div class="moveup"> <div class="ttypography"><p>No</p></div> </div> </div> <div class="reply info"> <a class="comment-602006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602006"> <li> <div class="comment"> <table class="comment-table" commentId="602113" commentParentId="602006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602113" href="?#comment-602113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602113" class="CommentVoteFrame" data-commentRating="20" 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: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-602113"> <div class="moveup"> <div class="ttypography"><p>Yes</p></div> </div> </div> <div class="reply info"> <a class="comment-602113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602113"> <li> <div class="comment"> <table class="comment-table" commentId="602122" commentParentId="602113"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602122" href="?#comment-602122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602113" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602122" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" 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;">-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-602122"> <div class="moveup"> <div class="ttypography"><p>No is no</p></div> </div> </div> <div class="reply info"> <a class="comment-602122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602122"> <li> <div class="comment"> <table class="comment-table" commentId="602331" commentParentId="602122"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602331" href="?#comment-602331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602331" class="CommentVoteFrame" data-commentRating="41" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602331"> <div class="moveup"> <div class="ttypography"><p>Dumb is dumb</p></div> </div> </div> <div class="reply info"> <a class="comment-602331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602331"> <li> <div class="comment"> <table class="comment-table" commentId="602624" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 15:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602624" href="?#comment-602624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602624" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" 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;">-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-602624"> <div class="moveup"> <div class="ttypography"><p>Who is dumb there?</p></div> </div> </div> <div class="reply info"> <a class="comment-602624 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602624 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602624"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604121" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:02">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604121" href="?#comment-604121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604121" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604121"> <div class="moveup"> <div class="ttypography"><p>BABA IS YOU</p></div> </div> </div> <div class="reply info"> <a class="comment-604121 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604121 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604121"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604142" commentParentId="604121"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604142" href="?#comment-604142" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604142" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604142"> <div class="moveup"> <div class="ttypography"><p>Who is BABA?</p></div> </div> </div> <div class="reply info"> <a class="comment-604142 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604142 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604142"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604648" commentParentId="604142"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Suleyman.A" style="position: relative;"> <img src='https://userpic.codeforces.org/82791/avatar/fc8479c7406b79a3.jpg'/> </a> <div><a href="/profile/Suleyman.A" title="Expert Suleyman.A" class="rated-user user-blue">Suleyman.A</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604648" href="?#comment-604648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604142" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604648" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="82791" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604648"> <div class="moveup"> <div class="ttypography"><p>He is husband of your mother</p></div> </div> </div> <div class="reply info"> <a class="comment-604648 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604648 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604648"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602019" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602019" href="?#comment-602019" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602019" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602019"> <div class="moveup"> <div class="ttypography"><p>Its always better if editorial provides code or snippet about their approach</p></div> </div> </div> <div class="reply info"> <a class="comment-602019 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602019 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602019"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rajiv_kale" style="position: relative;"> <img src='https://userpic.codeforces.org/758545/avatar/575c69bbc5b5a715.jpg'/> </a> <div><a href="/profile/rajiv_kale" title="Newbie rajiv_kale" class="rated-user user-gray">rajiv_kale</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601975" href="?#comment-601975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601975" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601975" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="758545" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601975"> <div class="moveup"> <div class="ttypography"><p>Good editorial. I especially liked those behind stories.</p></div> </div> </div> <div class="reply info"> <a class="comment-601975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601975"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601992" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601992" href="?#comment-601992" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601992" class="CommentVoteFrame" data-commentRating="8" 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;">+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-601992"> <div class="moveup"> <div class="ttypography"><p>My E looks very different, now I'm wondering if it's correct.</p><p>Let's focus only on one big strongly connected component. For each vertex $$$V$$$ all the vertices which point to $$$V$$$ are ordered in a path. So, maybe it's possible to somehow form a cycle from all the vertices from the SCC. Let's take any vertex $$$V$$$. Now, from all the vertices which point to the $$$V$$$ let's take the last one on this path, let's call it $$$U$$$. Fix $$$U$$$ before $$$V$$$ on this cycle. Now, in the same manner, find a vertex that will be before $$$U$$$. And so on until we have a full cycle. My guess is that it's correct and that after this process which vertex points to some interval on the cycle which starts in this vertex. With such a form of the graph, we can easily calculate the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-601992 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601992 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601992"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602013" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602013" href="?#comment-602013" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602013" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-62" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-602013"> <div class="moveup"> <div class="ttypography"><p>Im not gonna lie but div2 was not interesting at all, problems D and E just required some basic observation. I hope future rounds require some more algorithmic skills to solve D and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-602013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602013"> <li> <div class="comment"> <table class="comment-table" commentId="602039" commentParentId="602013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602039" href="?#comment-602039" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602039" class="CommentVoteFrame" data-commentRating="100" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+100</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602039"> <div class="moveup"> <div class="ttypography"><p>How come did you only solve A then?</p></div> </div> </div> <div class="reply info"> <a class="comment-602039 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602039 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602039"> <li> <div class="comment"> <table class="comment-table" commentId="602102" commentParentId="602039"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602102" href="?#comment-602102" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602039" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602102" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-40" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602102"> <div class="moveup"> <div class="ttypography"><p>The point is not how many problems I solved or not but about the quality of problems, pls dont divert issues like this. (btw that submission to A is after contest :p)</p></div> </div> </div> <div class="reply info"> <a class="comment-602102 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602102 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602102"> <li> <div class="comment"> <table class="comment-table" commentId="602128" commentParentId="602102"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602128" href="?#comment-602128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602102" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602128" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602128"> <div class="moveup"> <div class="ttypography"><p>OK, I'm sorry.</p><p>Well, I thought they were good :D. It's kinda subjective. Who's to say &quot;making observations&quot; is worse than &quot;algorithmic skills&quot;? I don't think it's so much about &quot;quality of problems&quot; than &quot;style of problems&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-602128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602128"> <li> <div class="comment"> <table class="comment-table" commentId="602144" commentParentId="602128"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602144" href="?#comment-602144" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602144" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602144"> <div class="moveup"> <div class="ttypography"><p>I agree it's about style problems and I also liked the problems today. However I do agree with <a class="rated-user user-black" href="/profile/bored69" title="Unrated, bored69">bored69</a> that imo too many problems are extremely short to code while relying solely on observation. While I know many people enjoy the short to code problems, it is called _code_forces after all, so I think the solution should be longer than 10 lines to solve the problem, and I would enjoy getting to use some standard algorithms more often as long as the problem is still not straight application</p></div> </div> </div> <div class="reply info"> <a class="comment-602144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602144"> <li> <div class="comment"> <table class="comment-table" commentId="602407" commentParentId="602144"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lessmeaning" style="position: relative;"> <img src='https://userpic.codeforces.org/400632/avatar/4aeb556dedbc357a.jpg'/> </a> <div><a href="/profile/lessmeaning" title="Master lessmeaning" class="rated-user user-orange">lessmeaning</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602407" href="?#comment-602407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602144" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602407" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="400632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602407"> <div class="moveup"> <div class="ttypography"><p>Another Radewoosh's pawn</p></div> </div> </div> <div class="reply info"> <a class="comment-602407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602407"> <li> <div class="comment"> <table class="comment-table" commentId="602903" commentParentId="602407"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602903" href="?#comment-602903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602407" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602903" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602903"> <div class="moveup"> <div class="ttypography"><p>Maybe Radewoosh is my pawn ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-602903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602903"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602017" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602017" href="?#comment-602017" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602017" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602017"> <div class="moveup"> <div class="ttypography"><p>In Div 2-D explanation, I am not able to understand e-l+m part. Can someone help? </p></div> </div> </div> <div class="reply info"> <a class="comment-602017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602017"> <li> <div class="comment"> <table class="comment-table" commentId="602185" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602185" href="?#comment-602185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602185" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602185"> <div class="moveup"> <div class="ttypography"><p>The key construction in the editorial is that for every leaf i, the edge between i and its parent is xor(path(root,parent(i))). This construction guarantees different weights with one exception, what if multiple leaves have same parent? In that case we'll have only one extra distinct weight for all leaves with a common parent. So instead of including weights for all the leaves, we'll include weights only for their parents. Hence, first assume all edges as distinct and include them all(e) , then remove all leaves(l) and finally add those parents (which are non-leaf nodes with atleast one child as leaf (m)). So, we get e-l+m.</p></div> </div> </div> <div class="reply info"> <a class="comment-602185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602185"> <li> <div class="comment"> <table class="comment-table" commentId="602260" commentParentId="602185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602260" href="?#comment-602260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602185" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602260"> <div class="moveup"> <div class="ttypography"><p>I checked your solution. I am having some doubts. 1- Why did you choose your node as the vertex with a maximum degree? 2- The minimum f condition says if only odd paths are there, the minimum f is 1. forex. like 1--2--3--4(-- is an edge), how only one number can ensure bitwise XOR of 0?</p></div> </div> </div> <div class="reply info"> <a class="comment-602260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602260"> <li> <div class="comment"> <table class="comment-table" commentId="602286" commentParentId="602260"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602286" href="?#comment-602286" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602260" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602286" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602286"> <div class="moveup"> <div class="ttypography"><ol> <li>I had a different approach when I started coding, so i start with that node with maximum degre. In my approach, the necessary condition is that root node should not be leaf, if it is I'll not count one leaf in my dfs leading to a wrong answer.</li> <li>Minimum condition for f is, all leaf nodes should be at a distance of same parity from root, so that every pair of leaves are separated by even no. Of edges.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-602286 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602286 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602286"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602209" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602209" href="?#comment-602209" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602209" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602209"> <div class="moveup"> <div class="ttypography"><p>What about the case when edges with same weight are counted twice? In the picture Observation 3, the edges (1)-(2) and (2)-(6) should have the same weight. But the formula will count them as separate weights. Can someone please explain&gt;</p></div> </div> </div> <div class="reply info"> <a class="comment-602209 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602209 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602209"> <li> <div class="comment"> <table class="comment-table" commentId="602232" commentParentId="602209"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:52">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602232" href="?#comment-602232" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602209" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602232" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602232"> <div class="moveup"> <div class="ttypography"><p>No, it won't be counted twice. edges 1-2 and 2-6 are first removed by subtracting l (e-l) and then added once for their common parent 2(non-leaf node with 2 leaves) through m (e-l+m)</p></div> </div> </div> <div class="reply info"> <a class="comment-602232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602232"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602029" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaaven" style="position: relative;"> <img src='https://userpic.codeforces.org/851917/avatar/442eaf7f5f3f896b.jpg'/> </a> <div><a href="/profile/vaaven" title="Master vaaven" class="rated-user user-orange">vaaven</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602029" href="?#comment-602029" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602029" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="851917" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602029"> <div class="moveup"> <div class="ttypography"><p>Thank you for interesting and hard problems, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a>!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-602029 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602029 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602029"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602042" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602042" href="?#comment-602042" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602042" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602042" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602042"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1338/problem/B" title="Codeforces Round 633 (Div. 1)">1338B - Edge Weight Assignment</a> Dont get it how the construction works at all. Should't there be some recursion as we do a dfs? How/where do we start, and what to do in &quot;each step&quot;, assuming there are steps?</p></div> </div> </div> <div class="reply info"> <a class="comment-602042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602042"> <li> <div class="comment"> <table class="comment-table" commentId="602203" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AdsT" style="position: relative;"> <img src='https://userpic.codeforces.org/639570/avatar/f12b9c2694f9e204.jpg'/> </a> <div><a href="/profile/AdsT" title="Expert AdsT" class="rated-user user-blue">AdsT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602203" href="?#comment-602203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602203" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="639570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602203"> <div class="moveup"> <div class="ttypography"><p>I agree, everyone seemed to have just done the same thing, take one from the back and one from the front, I just am not able to prove this. How do I come to this conclusion?</p></div> </div> </div> <div class="reply info"> <a class="comment-602203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602203"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602348" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602348" href="?#comment-602348" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602348" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602348"> <div class="moveup"> <div class="ttypography"><p>This is a way that I came up with to always satisfy 3 distinct colors for every tree.</p><p>Choose a leaf (called $$$u$$$) and choose the connected node with this leaf (called $$$r$$$ and obviously this node won't be a leaf, as $$$n &gt;= 3$$$) as the root.</p><p>What we are going to construct is we are trying to make: $$$ xor(path(r, v)) = xor(path(r, u)) $$$ for every leaf $$$v$$$. Because when $$$ xor(path(r, v)) = xor(path(r, u)) $$$ then $$$ xor(path(r, v_1)) = xor(path(r, v_2)) ( = xor(path(r, u)))$$$ for every pair of leaves.</p><p>We have $$$xor(path(r, v_1)) = xor(path(r, v_2)) $$$ $$$\Leftrightarrow (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_1))) = (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_2)))$$$ $$$\Leftrightarrow xor(path(lca(v_1, v_2), v_1)) = xor(path(lca(v_1, v_2), v_2)) \Rightarrow$$$ Satisfy the condition</p><p>So here is what I do:</p> <ol> <li>Let the edge between $$$r$$$ and $$$u$$$ have weight $$$1$$$.</li> <li>We dfs from $$$r$$$, save the prefix $$$xor$$$ value from $$$r$$$ to the node $$$p$$$ we are at and dfs to node children $$$v$$$ of $$$p$$$:</li> </ol> <ul> <li>If $$$v$$$ is a leaf, then we need to assign this edge so that the prefix $$$xor$$$ value will be equal to $$$1$$$ ($$$ = xor(path(r, u))$$$).</li> <li>If $$$v$$$ is not a leaf, then we assign $$$2$$$ to that edge. Why? Because we need to get rid of the case when the prefix $$$xor$$$ value at node $$$p$$$ (parent of leaf $$$v$$$, for example) is equal to $$$1$$$ ($$$ = xor(path(r, u))$$$) and whatever we assign $$$edge(p, v)$$$ we cannot make the prefix $$$xor$$$ value at leaf $$$v$$$ equal to $$$1$$$ anymore.</li> </ul><p>P/s: Ask me anything that you may not understand ^^. </p></div> </div> </div> <div class="reply info"> <a class="comment-602348 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602348 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602348"> <li> <div class="comment"> <table class="comment-table" commentId="602440" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602440" href="?#comment-602440" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602440" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602440"> <div class="moveup"> <div class="ttypography"><p>Thanks!</p><p>Now I think the key observation to come up with all of this is the parity of distances of three leafs.</p><p>$$$parity(dist(l1,l2)) \oplus parity(dist(l1,l3)) = parity(dist(l2,l3))$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-602440 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602440 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602440"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603442" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603442" href="?#comment-603442" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603442" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603442"> <div class="moveup"> <div class="ttypography"><p>I didnt get the part where you assign 2 to the edge that is not a leaf.</p></div> </div> </div> <div class="reply info"> <a class="comment-603442 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603442 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603442"> <li> <div class="comment"> <table class="comment-table" commentId="603446" commentParentId="603442"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603446" href="?#comment-603446" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603442" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603446"> <div class="moveup"> <div class="ttypography"><p>Consider all the edges which not connect any leaf are assigned $$$2$$$, then all the prefix $$$xor$$$ value at node $$$p$$$ (not a leaf) will be either $$$...000$$$ or $$$...010$$$. So when we go to a leaf we can assign a possible value to make the prefix $$$xor$$$ equal to $$$...001$$$. </p><p>Suppose we don't assign $$$2$$$ but $$$1$$$ or $$$3$$$ then there will be the case when at node $$$p$$$ (not a leaf but have a leaf child) the prefix $$$xor$$$ may be $$$...001$$$ and go to node $$$v$$$ (the leaf child of $$$p$$$) whether we assign the edge $$$1$$$, $$$2$$$ or $$$3$$$ then the prefix $$$xor$$$ can't be $$$...001$$$ anymore.</p><p>Sorry for my bad English !</p></div> </div> </div> <div class="reply info"> <a class="comment-603446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603446"> <li> <div class="comment"> <table class="comment-table" commentId="603451" commentParentId="603446"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603451" href="?#comment-603451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603446" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603451" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603451"> <div class="moveup"> <div class="ttypography"><p>Thanks to your quick reply,I am able to understand it.Can you please suggest some resources or something that would help me in solving problem cause' I am only able to solve upto problem c everytime?</p></div> </div> </div> <div class="reply info"> <a class="comment-603451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603451"> <li> <div class="comment"> <table class="comment-table" commentId="603456" commentParentId="603451"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603456" href="?#comment-603456" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603451" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603456" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603456"> <div class="moveup"> <div class="ttypography"><p>My suggestions: Solve problems and reflect upon what you have done wrong ... or what's observation you missed (And note them back obviously) ... or new algorithms (search and read for them and do 3 — 5 problems about that topic). Sometimes algorithm have signs, try to see that.</p><p>P/s: It's my own opinion anyway. Good luck &lt;3.</p></div> </div> </div> <div class="reply info"> <a class="comment-603456 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603456 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603456"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606855" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Darooha" style="position: relative;"> <img src='https://userpic.codeforces.org/27157/avatar/c4be2a4212ec87ed.jpg'/> </a> <div><a href="/profile/Darooha" title="Pupil Darooha" class="rated-user user-green">Darooha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606855" href="?#comment-606855" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606855" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="27157" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-606855"> <div class="moveup"> <div class="ttypography"><p>To everybody: The editorial has this update. It makes the problem much simpler:</p><p>(Update) There is an another way to approach, provided by Darooha.</p><p>If you label vertices instead of edges where all leaves have same label and none of neighbors have same label, then you can consider edge weight as xor of two vertices' labels, so this is basically equivalent to original problem.</p><p>Now for minimum, you can see that labelling 0 to leaves, and 1,2 to non-leaves are enough, so you can prove minimum value of f is at most 3. In same manner, you can try parity checking to check if f value can be 1 or not.</p><p>For maximum, assign 0 to all leaves and assign all different values(21,22,...) to non-leaf vertices, then you can see all edge weights(except leaves connected to same vertex) are different.</p></div> </div> </div> <div class="reply info"> <a class="comment-606855 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606855 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606855"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rojansudev700" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rojansudev700" title="Newbie rojansudev700" class="rated-user user-gray">rojansudev700</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602066" href="?#comment-602066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1236502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602066"> <div class="moveup"> <div class="ttypography"><p>Can anybody please explain problem A and its editorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-602066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602066"> <li> <div class="comment"> <table class="comment-table" commentId="602098" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602098" href="?#comment-602098" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602098"> <div class="moveup"> <div class="ttypography"><p>You may refer to the picture in the editorial. In this picture, if you put the red one in, you will find there is only one way to fill it( also described in the picture). Hence, since there are N different ways for putting the red one in, the answer is simply N.</p></div> </div> </div> <div class="reply info"> <a class="comment-602098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602098"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602157" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Apr/12/2020 21:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602157" href="?#comment-602157" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602157" 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-602157"> <div class="moveup"> <div class="ttypography"><p>Consider you want to find the answer for shape with size N. Let's say you put a Vertical diamond initially then places of all other diamonds are decided. So this is 1 way to put diamonds.</p><p>The other way is to put two horizontal diamonds on top left and bottom left and then we are have to find ways to puts diamonds in a shape of size N-1.</p><p>Ans(i) = 1 + Ans(i-1) <br /> {1 for the way in which vertical diamond is placed on the leftmost position}</p><p>Ans(i) = 1 + Ans(i-1) = i, given ans(1) =1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602157"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602093" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bayweiheng" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bayweiheng" title="Grandmaster bayweiheng" class="rated-user user-red">bayweiheng</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602093" href="?#comment-602093" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602093" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="533715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602093"> <div class="moveup"> <div class="ttypography"><p>In Div1E, How can we calculate the contribution from vertices with no indegree? If v has no indegree, then dis(u,v) is known but how do we find dis(v,u)? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-602093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602093"> <li> <div class="comment"> <table class="comment-table" commentId="602110" commentParentId="602093"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602110" href="?#comment-602110" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602093" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602110" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602110"> <div class="moveup"> <div class="ttypography"><p>If $$$u$$$ has no in-degree then $$$dis(u,v)=1, dis(v,u)=614n$$$ for all $$$u\neq v$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602110 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602110 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602110"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602145" href="?#comment-602145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602145" 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="602145" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602145"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">E intuition?</b><div class="spoiler-content" style="display: none;"><p>Assume that all nodes have positive in-degree. Then we can arrange the nodes in a cycle $$$c_0,c_1,\ldots, c_{n-1}$$$ such that $$$c_i$$$ has edges to $$$c_{i+1},c_{i+2},\ldots,c_{(i+out(i))\pmod{n}}$$$ where $$$out(i)$$$ denotes the out-degree of node $$$c_i$$$. To find this cycle, start with any vertex $$$x$$$ and topologically sort $$$in(x)$$$. Then repeat with the last node of $$$in(x)$$$ (with respect to the sorted order).</p><p>For all $$$i$$$, $$$out(i)&gt;0$$$ and $$$out(i)\le out((i+1)\pmod{n})+1$$$. Suppose that $$$i&lt;j$$$. Then $$$out(i)+i\le out(j)+j$$$ and the distance from $$$c_j$$$ to $$$c_i$$$ is three iff $$$out(i)+i=out(j)+j$$$. Otherwise, it's one or two.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-602145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602145"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602151" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misqwerty" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/misqwerty" title="Newbie misqwerty" class="rated-user user-gray">misqwerty</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602151" href="?#comment-602151" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602151" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="727011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602151"> <div class="moveup"> <div class="ttypography"><p>Do anyone else other than me recognize this submission as a hack for a hack and there were two successful hacking attempts. That's a <strong>cheat</strong>. <a href="/contest/1339/submission/76401969" title="Submission 76401969 by SIBshaan">76401969</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602151 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602151 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602151"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602165" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602165" href="?#comment-602165" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602165" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602165"> <div class="moveup"> <div class="ttypography"><p>how to find editorial in english for Atcoder Begginer contest 162 on their website it's in japanese..</p></div> </div> </div> <div class="reply info"> <a class="comment-602165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602165"> <li> <div class="comment"> <table class="comment-table" commentId="602170" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:39">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602170" href="?#comment-602170" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602170" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602170"> <div class="moveup"> <div class="ttypography"><p>Pay attention to the red line written on the first page of the Japanese editorial .</p></div> </div> </div> <div class="reply info"> <a class="comment-602170 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602170 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602170"> <li> <div class="comment"> <table class="comment-table" commentId="602195" commentParentId="602170"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602195" href="?#comment-602195" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602170" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602195" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602195"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602195 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602195 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602195"> <li> <div class="comment"> <table class="comment-table" commentId="602248" commentParentId="602195"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602248" href="?#comment-602248" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602195" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602248" 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-602248"> <div class="moveup"> <div class="ttypography"><p>I've solved A,B,C,D if you want, i can tell u how to solve them</p></div> </div> </div> <div class="reply info"> <a class="comment-602248 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602248 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602248"> <li> <div class="comment"> <table class="comment-table" commentId="602255" commentParentId="602248"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602255" href="?#comment-602255" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602248" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602255" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602255" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602255"> <div class="moveup"> <div class="ttypography"><p>please tell me how you solved D</p></div> </div> </div> <div class="reply info"> <a class="comment-602255 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602255 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602255"> <li> <div class="comment"> <table class="comment-table" commentId="602270" commentParentId="602255"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602270" href="?#comment-602270" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602255" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602270" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602270" 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-602270"> <div class="moveup"> <div class="ttypography"><p>So you gonna fix i and k such that S[i] != S[k]. So in the range [i + 1, k — 1] you should find the number of characters C different from S[i] as well as S[j]. So, for example, if S[i] = 'R' and S[k] = 'G', C = 'B'. So these different characters can be found using segment tree, maybe there is other method too. Also you should check for the second condition, if (k — i) % 2 == 0 and S[(i + k) / 2] == c, you gonna decrement that number by one.</p></div> </div> </div> <div class="reply info"> <a class="comment-602270 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602270 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602270"> <li> <div class="comment"> <table class="comment-table" commentId="602272" commentParentId="602270"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602272" href="?#comment-602272" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602270" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602272" 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-602272"> <div class="moveup"> <div class="ttypography"><p>That's my solution, but I think there is a better solution described in the following video: <a href="https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s">https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602272"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602172" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602172" href="?#comment-602172" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602172" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602172"> <div class="moveup"> <div class="ttypography"><p>Btw, why ask this here xD</p></div> </div> </div> <div class="reply info"> <a class="comment-602172 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602172 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602172"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602167" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602167" href="?#comment-602167" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602167" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602167"> <div class="moveup"> <div class="ttypography"><p>Could someone elaborate a bit more the intuition behind Div1D and how to implement it?</p></div> </div> </div> <div class="reply info"> <a class="comment-602167 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602167 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602167"> <li> <div class="comment"> <table class="comment-table" commentId="602265" commentParentId="602167"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602265" href="?#comment-602265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602167" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602265" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602265" class="CommentVoteFrame" data-commentRating="42" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+42</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602265"> <div class="moveup"> <div class="ttypography"><p>I approached this problem by considering what happens if we only consider the minimum connected subgraph containing the answer, where the answer is the set of nodes $$$S$$$ that form the nested rubber bands. First, consider each $$$v\in S$$$ as a circle, so we have $$$|S|$$$ nested circles. The other vertices of this minimum connected subgraph must contribute to connecting two or more circles, and we can consider them as line segments. </p><p>Colour the line segments red and the circles blue. Then, we'll see that the red vertices lie on a path, because we can trace out a path in this alternate representation of the tree. Furthermore, the blue vertices form an independent set, and each is adjacent to at least one red vertex.</p><p>DP states:</p><p>For each state, I suppose that the red vertices lie on a path in the subtree rooted at u with one endpoint at u.</p> <ul> <li><p>take[u] = number of blue vertices if u is blue</p></li> <li><p>skip[u] = number of blue vertices if u is red</p></li> </ul><p>DP transitions:</p> <ul> <li><p><code>take[u] = max(1 + skip[child])</code>. Since we're interested in a path, we take the max.</p></li> <li><p><code>skip[u] = max(#children-1 + max(take[child], skip[child]))</code>. If we colour u red, then we can colour all its uncoloured neighbours blue, but we still want to be able to choose for the next node in the path.</p></li> </ul><p>To get the answer, consider a path rooted at u. We need to know the best two values of <code>take[child]</code> and <code>max(take[child], skip[child])</code> to find the answer for such a path.</p><p>I'm sure you could fit the dp and get the solution in one dfs function, but here's my rather long and verbose code: <a href="https://codeforces.com/contest/1338/submission/76420228">https://codeforces.com/contest/1338/submission/76420228</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602265"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602182" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gouravmajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1380497/avatar/470f8f4adfac9b5d.jpg'/> </a> <div><a href="/profile/gouravmajee" title="Newbie gouravmajee" class="rated-user user-gray">gouravmajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602182" href="?#comment-602182" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602182" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1380497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602182"> <div class="moveup"> <div class="ttypography"><p>this was my first contest :) I passed question 1. </p></div> </div> </div> <div class="reply info"> <a class="comment-602182 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602182 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602182"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602191" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aid" style="position: relative;"> <img src='https://userpic.codeforces.org/106240/avatar/ab90218e19d9e731.jpg'/> </a> <div><a href="/profile/aid" title="International Grandmaster aid" class="rated-user user-red">aid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602191" href="?#comment-602191" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602191" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="106240" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602191"> <div class="moveup"> <div class="ttypography"><p>$$$O(n^2\log(n))$$$ can be squeezed in E: <a href="/contest/1338/submission/76419686" title="Submission 76419686 by aid">76419686</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-602191 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602191 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602191"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602210" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cdc.biobot" style="position: relative;"> <img src='https://userpic.codeforces.org/152957/avatar/23e3d83914fae0f6.jpg'/> </a> <div><a href="/profile/cdc.biobot" title="Newbie cdc.biobot" class="rated-user user-gray">cdc.biobot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602210" href="?#comment-602210" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602210" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602210" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="152957" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602210"> <div class="moveup"> <div class="ttypography"><p>I beg your pardon, but I think problem statement of div2A should have been a bit clearer in explaining the term 'covering differently'. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-602210 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602210 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602210"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602211" href="?#comment-602211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602211" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602211"> <div class="moveup"> <div class="ttypography"><p>In Div2 D for finding the maximum f value, what is the proof that there is no other construction possible that can possibly have more distinct weights? For example, consider a tree with the non-leaf nodes having degree 4. In the observation 3 picture, we can add to node 2, a replica structure of its child node 3. That will make node 2's degree 4. How to prove for this case(and in general) that the maximum value of f will not exceed e-l+m?</p></div> </div> </div> <div class="reply info"> <a class="comment-602211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602211"> <li> <div class="comment"> <table class="comment-table" commentId="602241" commentParentId="602211"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602241" href="?#comment-602241" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602211" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602241" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602241"> <div class="moveup"> <div class="ttypography"><p>Because that's the upper bound of the value.</p><p>Every edge that isn't adjacent to a leaf doesn't matter. Edges for leaves that are adjacent to the same non-leaf vertex need to be equal. That can be counted as in the editorial because — (leaves — non-leaf vertex adjacent to a leaf) is exactly the number of edges to leaves that are free to receive values.</p></div> </div> </div> <div class="reply info"> <a class="comment-602241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602241"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602221" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602221" href="?#comment-602221" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602221" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602221"> <div class="moveup"> <div class="ttypography"><p>hi..what is the maximum time in which it's good to solve div2 — A and B.. because i'm practicing only DIV2 A and B question in virtual contest..and still took more than 1 h to solve both...some time i failed to solve B.. Thanks in advance..</p></div> </div> </div> <div class="reply info"> <a class="comment-602221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602221"> <li> <div class="comment"> <table class="comment-table" commentId="602497" commentParentId="602221"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602497" href="?#comment-602497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602221" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602497"> <div class="moveup"> <div class="ttypography"><p>See this round was tough, but I think top coders take max 15 min for both, at my rating I think even 30 mins would be fine and for you, 45-60 min is the max you should ideally take</p></div> </div> </div> <div class="reply info"> <a class="comment-602497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602497"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602236" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Muhammad98" style="position: relative;"> <img src='https://userpic.codeforces.org/697747/avatar/2c13087bfd195af6.jpg'/> </a> <div><a href="/profile/Muhammad98" title="Specialist Muhammad98" class="rated-user user-cyan">Muhammad98</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602236" href="?#comment-602236" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="697747" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602236"> <div class="moveup"> <div class="ttypography"><p>The only Div2A that I couldn't solve during the round XD</p></div> </div> </div> <div class="reply info"> <a class="comment-602236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602236"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602238" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602238" href="?#comment-602238" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602238" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602238"> <div class="moveup"> <div class="ttypography"><p>Nice editorial and pictures! <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> One suggestion: It'll be easier to read d1E if you use lowercase letters for vertices and upper case letters for sets.</p></div> </div> </div> <div class="reply info"> <a class="comment-602238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602238"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gjaiswal108" style="position: relative;"> <img src='https://userpic.codeforces.org/756634/avatar/f398cd162ff7d60f.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/gjaiswal108" title="Expert gjaiswal108" class="rated-user user-blue">gjaiswal108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602251" href="?#comment-602251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602251" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756634" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602251"> <div class="moveup"> <div class="ttypography"><p><code>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this</code></p><p>Can anyone tell me what is meaning of OEIS in the story of D2E ?</p></div> </div> </div> <div class="reply info"> <a class="comment-602251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602251"> <li> <div class="comment"> <table class="comment-table" commentId="602259" commentParentId="602251"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/blitzitout" style="position: relative;"> <img src='https://userpic.codeforces.org/505681/avatar/39b2976ffc156007.jpg'/> </a> <div><a href="/profile/blitzitout" title="Expert blitzitout" class="rated-user user-blue">blitzitout</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602259" href="?#comment-602259" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602251" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602259" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602259" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="505681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602259"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/">This</a> is where you can find insights/recurrences of random sequences.</p></div> </div> </div> <div class="reply info"> <a class="comment-602259 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602259 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602259"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602252" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T-REXX" style="position: relative;"> <img src='https://userpic.codeforces.org/455170/avatar/f7f08af680e3156f.jpg'/> </a> <div><a href="/profile/T-REXX" title="Pupil T-REXX" class="rated-user user-green">T-REXX</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602252" href="?#comment-602252" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602252" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="455170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602252"> <div class="moveup"> <div class="ttypography"><p>I tried solving div2C by iterating through the array, whenever a[i]&gt;a[i+1] I added to all j=i+1 and j&lt;n lowest power of 2 possible to make it a[i]&lt;=a[i+1]. Lowest power was calculated using a vector of powers of 2. But it does not work, and I am unable to find out why. Can anyone help?</p></div> </div> </div> <div class="reply info"> <a class="comment-602252 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602252 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602252"> <li> <div class="comment"> <table class="comment-table" commentId="602471" commentParentId="602252"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bryceShakeair" style="position: relative;"> <img src='https://userpic.codeforces.org/872528/avatar/f8595cfd5dbfc474.jpg'/> </a> <div><a href="/profile/bryceShakeair" title="Specialist bryceShakeair" class="rated-user user-cyan">bryceShakeair</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602471" href="?#comment-602471" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602252" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602471" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872528" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602471"> <div class="moveup"> <div class="ttypography"><p>try 1 0 1 0 1 0 The optimal answer is x = 1 i.e. select indexes 2 , 4 ,6 you get 1 1 1 1 1 1 I hope that is clear </p></div> </div> </div> <div class="reply info"> <a class="comment-602471 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602471 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602471"> <li> <div class="comment"> <table class="comment-table" commentId="604684" commentParentId="602471"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604684" href="?#comment-604684" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602471" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604684" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604684"> <div class="moveup"> <div class="ttypography"><p>Thanks. </p></div> </div> </div> <div class="reply info"> <a class="comment-604684 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604684 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604684"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602282" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant_raja" style="position: relative;"> <img src='https://userpic.codeforces.org/742080/avatar/101f3740a4030218.jpg'/> </a> <div><a href="/profile/nishant_raja" title="Pupil nishant_raja" class="rated-user user-green">nishant_raja</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602282" href="?#comment-602282" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602282" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742080" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602282"> <div class="moveup"> <div class="ttypography"><p>Can anyone briefly explain the problem &quot;Powered Addition&quot;, I mean full approach and walk through an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-602282 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602282 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602282"> <li> <div class="comment"> <table class="comment-table" commentId="602498" commentParentId="602282"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jbs1jbs1jbs1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/jbs1jbs1jbs1" title="Specialist jbs1jbs1jbs1" class="rated-user user-cyan">jbs1jbs1jbs1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602498" href="?#comment-602498" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602282" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602498" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602498"> <div class="moveup"> <div class="ttypography"><p>My approach was as follows:</p><p>Let's say that the list is <code>[1, 7, 6, 5]</code>. We go through and we look at all the pairs <code>(a[i], a[i+1])</code>. We start with <code>(1,7)</code>. It satisfies the property of being non-decreasing, so we do nothing. Next, we go to <code>(7, 6)</code>. <code>6 &lt; 7</code>, meaning we have to add something to &quot;6&quot; to make it bigger. I assert (and will explain below the reason why), that it is possible and optimal to convert the &quot;6&quot; into a &quot;7&quot;. The list then becomes <code>[1, 7, 7, 5]</code>. Next, we look at the final pair <code>(7, 5)</code> and do the same: convert the &quot;5&quot; to a &quot;7&quot;, so that the final list becomes [1, 7, 7, 7].</p><p>When we convert a pair (a, b) to the pair (a, a), it means that we need to add some quantity (a-b) to it. If that quantity is 18, for example, then we can do this with 16 + 2 = 2^4 + 2^1. If that quantity is 15, we can do this with 2^0 + 2^1 + 2^2 + 2^3. In general, there is exactly one way to do the addition of distinct powers of 2 to get from one number to another.</p><p>You can find out which powers of 2 you need to add together by converting the difference into binary. The definition of binary is that where there is a &quot;1&quot; you can add the relevant power of 2.</p><p>In any case, I'm just saying that it is always <strong>possible</strong> to do this, and it doesn't matter what the exact powers of 2 are, you just need to know what the biggest power of 2 needed will be. This is because if you're using a bigger power of 2, for example 2^5, it means that seconds 1, 2, 3, 4, 5, 6 have already happened, so you could have, in the past, added 2^0, 2^1, 2^2, 2^3, 2^4 if you needed to do so.</p><p>The biggest power of 2 needed can be worked out by taking the logarithm base 2 of the difference, and then rounding down.</p><p>The code would then be something like this:</p> <pre><code>max_power_found = -1 for i in range(len(a) - 1): if a[i + 1] &lt; a[i]: difference = a[i] - a[i + 1] biggest_power = floor(log2(difference)) max_power_found = max(max_power_found, biggest_power) a[i + 1] = a[i] print(max_power_found + 1) </code></pre><p>Note that I initialise <code>max_power_found</code> to <code>-1</code> so that at the end, if nothing has happened because the array was already non-decreasing, it becomes <code>0</code> when you add 1.</p><p>Note also that even though we don't need to output the final array, I have the line <code>a[i + 1] = a[i]</code>. This is because the next pair needs to know about the change we just made.</p><p>There are <code>(n-1)</code> possible values of <code>i</code>, and for each one we do some constant time computation (logarithm base 2 is very fast), this is an O(n) solution.</p><p>Note that even if you didn't know about logarithms, you could probably do it very quickly because log2(10^5) is very small (though I haven't tested to make sure this doesn't TLE):</p> <pre><code>def biggest_power_needed(difference): # Outputs -1 if difference is 0. answer = -1 total = 0 while total &lt; difference: answer++ total += pow(2, answer) if total == difference: return answer else: return answer - 1 </code></pre><p>Again, we do <code>answer - 1</code> because we can use the smaller powers of 2 to increase it to exactly equal the difference.</p></div> </div> </div> <div class="reply info"> <a class="comment-602498 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602498 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602498"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shivamsaluja20" style="position: relative;"> <img src='https://userpic.codeforces.org/820036/avatar/92e6360dd7bc5c3d.jpg'/> </a> <div><a href="/profile/shivamsaluja20" title="Specialist shivamsaluja20" class="rated-user user-cyan">shivamsaluja20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602291" href="?#comment-602291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602291" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="820036" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602291"> <div class="moveup"> <div class="ttypography"><p>For the first time for problem A, it took me around 50 minutes to figure out and ironically that was the easiest one liner solution possible. Take the input and print it xD.</p></div> </div> </div> <div class="reply info"> <a class="comment-602291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EleCursity" style="position: relative;"> <img src='https://userpic.codeforces.org/388600/avatar/c667ca12cb3a5eb2.jpg'/> </a> <div><a href="/profile/EleCursity" title="Expert EleCursity" class="rated-user user-blue">EleCursity</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602292" href="?#comment-602292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602292" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="388600" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602292"> <div class="moveup"> <div class="ttypography"><p>Nice Editorial and nice problems. In <strong>div2E/div1C</strong> .I've found a strange pattern for the bits in the n-th triple . but I can't manage to code it during the contest. this is my code <a href="/contest/1339/submission/76432679" title="Submission 76432679 by EleCursity">76432679</a> .</p></div> </div> </div> <div class="reply info"> <a class="comment-602292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602297" href="?#comment-602297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602297"> <div class="moveup"> <div class="ttypography"><p>2D, I understand nothing, damn constructive problems and damn gap between C and D</p><p>&quot;Observation 1. You can prove that minimum value of f is at most 3, by following construction;&quot;</p><p>Well, how do we know there is no other construction where we would have 4 or more?</p><p>&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?</p><p>&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose</p></div> </div> </div> <div class="reply info"> <a class="comment-602297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602297"> <li> <div class="comment"> <table class="comment-table" commentId="602302" commentParentId="602297"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602302" href="?#comment-602302" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602297" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602302" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-602302"> <div class="moveup"> <div class="ttypography"><p>&quot;Well, how do we know there is no other construction where we would have 4 or more?&quot; The problem is asking for the minimum, there is a construction where $$$3$$$ is possible so the minimum is never greater than $$$3$$$</p><p>&quot;&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?&quot; Because we decided that that's how the construction should look like. Another example of a construction which would work is edges connecting a leaf having a weight of $$$2$$$ or $$$3$$$ depending on the parity leaf's depth and all other edges having a weight of $$$1$$$.</p><p>&quot;&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose&quot; Here's a proof: Notice that we can consider each bit separately and then an assignment works if the condition is satisfied for all bits. Let's say we choose numbers $$$a$$$ and $$$b$$$. If both $$$a$$$ and $$$b$$$ have some bit set to $$$1$$$ then that is the same as the $$$f=1$$$ case. If there is no bit which both $$$a$$$ and $$$b$$$ have set to 1 then that means that there is a bit which $$$a$$$ has set to $$$1$$$ and $$$b$$$ has set to $$$0$$$ and that there is a bit which $$$a$$$ has set to $$$0$$$ and $$$b$$$ has set to $$$1$$$, so each path needs to have an even number of both $$$a$$$ and $$$b$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602302 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602302 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602302"> <li> <div class="comment"> <table class="comment-table" commentId="602304" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 02:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602304" href="?#comment-602304" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602304" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602304"> <div class="moveup"> <div class="ttypography"><p>1-2) Oh, so it was about describing a generic technique of assigning values, not about the specific tree on the picture. Then it makes more sense</p><p>3) The confusing part here was that I thought it was about the number of a and b in the whole tree, not on the requested path, and didn't understand why.</p><p>I'll reread it with this in mind</p><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602304"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603392" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 02:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603392" href="?#comment-603392" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603392" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603392" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603392"> <div class="moveup"> <div class="ttypography"><p>I've got how we come up with f=3 from the comments</p><p>However I still don't understand the same part in the editorial &quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>On the picture we have a string of non-leaves, all of which have degree 3. And all the leaves obviously have degree 1 So following this statement we're supposed to have the same weights for every edge connecting a non-leaf to a leaf on the picture. However, this is not the case. </p></div> </div> </div> <div class="reply info"> <a class="comment-603392 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603392 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603392"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/feecIe6418" style="position: relative;"> <img src='https://userpic.codeforces.org/699680/avatar/da9b3b3e29a8fe7b.jpg'/> </a> <div><a href="/profile/feecIe6418" title="International Grandmaster feecIe6418" class="rated-user user-red">feecIe6418</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 03:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602320" href="?#comment-602320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602320" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="699680" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602320"> <div class="moveup"> <div class="ttypography"><p>Finally become master in this round. I like the problems! Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-602320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602334" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602334" href="?#comment-602334" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602334" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602334"> <div class="moveup"> <div class="ttypography"><p><strong>HELP! Please</strong></p><p>Hi, everyone! My friends has some trouble in his solutions, He has submitted this solution <a href="/contest/1339/submission/76367506" title="Submission 76367506 by zhouxiaolun">76367506</a> during the round, However, after the system pending test, He did not get an AC, but still the Pretest passed. The score for this problem was not added to my friends. He has submitted totally the same code just now, <a href="/contest/1339/submission/76438866" title="Submission 76438866 by zhouxiaolun">76438866</a>, and get an AC. Why did this happen? It has effected on my friends ratings, Where can I find the administor to solve the trouble? (sorry for my poor english)</p></div> </div> </div> <div class="reply info"> <a class="comment-602334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602334"> <li> <div class="comment"> <table class="comment-table" commentId="602339" commentParentId="602334"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iynaur87" style="position: relative;"> <img src='https://userpic.codeforces.org/561459/avatar/4516a52f8c97c0c2.jpg'/> </a> <div><a href="/profile/iynaur87" title="Candidate Master iynaur87" class="rated-user user-violet">iynaur87</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602339" href="?#comment-602339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602334" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602339" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="561459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602339"> <div class="moveup"> <div class="ttypography"><p>Weired. You can Send a message to <a href="https://codeforces.com/profile/MikeMirzayanov">https://codeforces.com/profile/MikeMirzayanov</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602339"> <li> <div class="comment"> <table class="comment-table" commentId="602345" commentParentId="602339"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602345" href="?#comment-602345" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602339" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602345" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602345"> <div class="moveup"> <div class="ttypography"><p>Thank you! You are so kind!</p></div> </div> </div> <div class="reply info"> <a class="comment-602345 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602345 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602345"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602341" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Raghu150999" style="position: relative;"> <img src='https://userpic.codeforces.org/714738/avatar/992860969ab6c84.jpg'/> </a> <div><a href="/profile/Raghu150999" title="Expert Raghu150999" class="rated-user user-blue">Raghu150999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602341" href="?#comment-602341" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602341" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714738" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602341"> <div class="moveup"> <div class="ttypography"><p>Great editorial. Thanks a lot!</p></div> </div> </div> <div class="reply info"> <a class="comment-602341 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602341 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602341"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602383" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aspiriner" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/aspiriner" title="Expert aspiriner" class="rated-user user-blue">aspiriner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602383" href="?#comment-602383" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602383" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1393907" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602383"> <div class="moveup"> <div class="ttypography"><p>in the div 2 B </p><p>i do not understand what the 'Sort the list, and make an oscillation centered on middle element like picture below.' means.</p><p>i just dont know how to sort it and what should i do in the next step.</p><p>please help me!</p></div> </div> </div> <div class="reply info"> <a class="comment-602383 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602383 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602383"> <li> <div class="comment"> <table class="comment-table" commentId="602411" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shisuko" style="position: relative;"> <img src='https://userpic.codeforces.org/554313/avatar/42772b63e4542d29.jpg'/> </a> <div><a href="/profile/Shisuko" title="Candidate Master Shisuko" class="rated-user user-violet">Shisuko</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602411" href="?#comment-602411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602411" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="554313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602411"> <div class="moveup"> <div class="ttypography"><p>Sort the elements in ascending order. Then you go smallest-&gt;largest-&gt;second smallest-&gt;second largest... and so on. If you draw it on paper, you can see that the gaps are always getting smaller because it's a subset of the previous gap.</p></div> </div> </div> <div class="reply info"> <a class="comment-602411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602411"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602415" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602415" href="?#comment-602415" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602415" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602415"> <div class="moveup"> <div class="ttypography"><p>Imagine the problem is the same, but differences between pairs must be non increasing instead of non decreasing ( | a_ i — a_i-1 | &gt;= | a_i-1 — a_i-2 | ). If we solve this, we can just reverse the answer and we will get an answer to the original problem. </p><p>Now, imagine we start with the biggest element to the left. What number should we add next to maximize their difference? The smallest element. So we add it. After that, what number not yet added would maximize the difference of the pair? The second biggest element, and it is not hard to see it will be smaller or equal than the first pair. If we continue to do this, we can get an answer.</p><p>So to build it we just sort the initial array and then build it in the following way: a[N] , a[1] , a[N-1] , a[2] , a[N-2] , a[3] ... </p><p>After this, don't forget to reverse the answer to solve the original problem. </p><p>Submission: <a href="/contest/1339/submission/76418078" title="Submission 76418078 by Diegogrc">76418078</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602415 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602415 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602415"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602445" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xD." style="position: relative;"> <img src='https://userpic.codeforces.org/918251/avatar/298a43e5c9cee8f5.jpg'/> </a> <div><a href="/profile/xD." title="Pupil xD." class="rated-user user-green">xD.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602445" href="?#comment-602445" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602445" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602445" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="918251" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602445"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/aspiriner" title="Pupil aspiriner">aspiriner</a> <strong>This picture may help you</strong> <img alt=" " src="/predownloaded/43/9a/439a03f6fa84e1a1c14509dbd3d5c4c88ee8d5a3.php" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-602445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602445"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602386" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misty1999" style="position: relative;"> <img src='https://userpic.codeforces.org/461973/avatar/bda2e09a046c8571.jpg'/> </a> <div><a href="/profile/misty1999" title="Specialist misty1999" class="rated-user user-cyan">misty1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602386" href="?#comment-602386" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602386" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="461973" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602386"> <div class="moveup"> <div class="ttypography"><p>First I thought maximal independent set in div1D, but got Wrong Answer on pretest 4.</p></div> </div> </div> <div class="reply info"> <a class="comment-602386 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602386 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602386"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuber_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/820815/avatar/9d558886908a602d.jpg'/> </a> <div><a href="/profile/cuber_coder" title="Master cuber_coder" class="rated-user user-orange">cuber_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602400" href="?#comment-602400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602400" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="820815" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602400"> <div class="moveup"> <div class="ttypography"><p>Great problemset, a beautifully written editorial, no queueforces, strong pretests and quick system testing makes it a wonderful round! Hope to participate in more rounds authored by you in future!</p><p>P.S. : my most special round till date since I finally reached CM !</p></div> </div> </div> <div class="reply info"> <a class="comment-602400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602400"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602404" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602404" href="?#comment-602404" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602404" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602404"> <div class="moveup"> <div class="ttypography"><p>can someone explain div2-C,i am not able to understand the editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-602404 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602404 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602404"> <li> <div class="comment"> <table class="comment-table" commentId="602437" commentParentId="602404"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602437" href="?#comment-602437" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602404" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602437" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602437"> <div class="moveup"> <div class="ttypography"><p>first of all find the max difference between any two number (O(n)). then you just need to count number of digits in it. which can be done using log2 of that difference. note: ceil function is to be used for ex: 2.5 would be rounded off to 3.</p><p>here's my code(which is actually someone else but I copied it and modified a little, but is self explanatory )</p><p><a href="https://codeforces.com/contest/1339/submission/76446573">https://codeforces.com/contest/1339/submission/76446573</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602437 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602437 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602437"> <li> <div class="comment"> <table class="comment-table" commentId="602494" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602494" href="?#comment-602494" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602494" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602494"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/FinalBoss_" title="Pupil FinalBoss_">FinalBoss_</a> Can you please explain why did you add 1 in log2(dis+1) ?</p><p>I guess dis is the max number required to add.Why +1 ?My first submission was same but i didnt add 1 it got wa.</p></div> </div> </div> <div class="reply info"> <a class="comment-602494 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602494 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602494"> <li> <div class="comment"> <table class="comment-table" commentId="602546" commentParentId="602494"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602546" href="?#comment-602546" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602494" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602546" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602546"> <div class="moveup"> <div class="ttypography"><p>yes dis is the max number required to add. log2(dis+1) is done because... we were asked to find 2^(x-1).</p><p>in case all numbers are equal and dis is 0 or if array is already increasing and dis is still 0, then log(0) becomes undefined. Now since we don't need actual value but ceiling of it so adding 1 to dis and then taking log will have same effect but also it will remove ambiguity of log(0).</p></div> </div> </div> <div class="reply info"> <a class="comment-602546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602546"> <li> <div class="comment"> <table class="comment-table" commentId="602650" commentParentId="602546"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602650" href="?#comment-602650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602546" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602650"> <div class="moveup"> <div class="ttypography"><p>Thanks, got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-602650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602650"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603609" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaibhavsingh100070" style="position: relative;"> <img src='https://userpic.codeforces.org/792197/avatar/6a8b6f989cc93e7d.jpg'/> </a> <div><a href="/profile/vaibhavsingh100070" title="Pupil vaibhavsingh100070" class="rated-user user-green">vaibhavsingh100070</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 09:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603609" href="?#comment-603609" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603609" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="792197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603609"> <div class="moveup"> <div class="ttypography"><p>Can you please explain for this test case n = 5 a = [ 1, 2, 1, 4, 1] For this output is ** 2**. How in 2 steps we will make this array non decreasing?</p></div> </div> </div> <div class="reply info"> <a class="comment-603609 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603609 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603609"> <li> <div class="comment"> <table class="comment-table" commentId="604681" commentParentId="603609"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604681" href="?#comment-604681" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603609" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604681" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604681" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604681"> <div class="moveup"> <div class="ttypography"><p>Same doubt. Hoping someone to answer.</p><p>Edit: Got it. Should have read the question carefully. It says select any indices not continuous indices.</p><p>for n=5 ans array [ 1 2 1 4 1 ] </p><p>Step 1: Select indices : Select 3 and 5 ( begins from 0) Step 2: Increase by 1 then by 2 ( 2^x-1 , put x=1 and then 2) So array becomes : 1 2 4 4 4 which is non-decreasing.</p></div> </div> </div> <div class="reply info"> <a class="comment-604681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604681"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602409" href="?#comment-602409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602409" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602409"> <div class="moveup"> <div class="ttypography"><p>I have doubt in 1339 B -Sorted Adjacent Differences: If the array is: -2 5 5 6 The answer will be 5 -2 5 6 which is wrong Please explain if i am wrong</p></div> </div> </div> <div class="reply info"> <a class="comment-602409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602409"> <li> <div class="comment"> <table class="comment-table" commentId="602428" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602428" href="?#comment-602428" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602428"> <div class="moveup"> <div class="ttypography"><p>it is wrong because the required condition is not fulfilled as your answer will make seqeunce like this 7&lt;=7&gt;1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602428"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602433" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mestu" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mestu" title="Expert Mestu" class="rated-user user-blue">Mestu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602433" href="?#comment-602433" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602433" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="922247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602433"> <div class="moveup"> <div class="ttypography"><p>For array -2 5 5 6 the answer will be 5 5 -2 6 </p></div> </div> </div> <div class="reply info"> <a class="comment-602433 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602433 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602433"> <li> <div class="comment"> <table class="comment-table" commentId="602473" commentParentId="602433"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602473" href="?#comment-602473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602433" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602473"> <div class="moveup"> <div class="ttypography"><p>yes,but according to tutorial it is printing 5-2 5 6</p></div> </div> </div> <div class="reply info"> <a class="comment-602473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602473"> <li> <div class="comment"> <table class="comment-table" commentId="602740" commentParentId="602473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602740" href="?#comment-602740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602740"> <div class="moveup"> <div class="ttypography"><p>according to tutorial it will print 5 5 -2 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-602740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602740"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602427" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/inazuma_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/inazuma_11" title="Newbie inazuma_11" class="rated-user user-gray">inazuma_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602427" href="?#comment-602427" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602427" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1335781" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602427"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain O(N) approach for div 2C ? I know how to do it in O(NlogN) but not in O(N)</p></div> </div> </div> <div class="reply info"> <a class="comment-602427 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602427 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602427"> <li> <div class="comment"> <table class="comment-table" commentId="602432" commentParentId="602427"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602432" href="?#comment-602432" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602427" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602432" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602432"> <div class="moveup"> <div class="ttypography"><p>While traversing the array keep a count of what maximum difference have you seen so far from the previous element i.e maximum value uptil that i minus the array value at that i. Then once you found the maximum difference than going for finding the position of the highest bit in this maximum difference. The ans is going to be the value of this highest bit + 1. Make sure to include the edge case that if the maximum difference is 0 then the ans is also 0.</p></div> </div> </div> <div class="reply info"> <a class="comment-602432 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602432 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602432"> <li> <div class="comment"> <table class="comment-table" commentId="602492" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602492" href="?#comment-602492" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602492" 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="602492" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602492"> <div class="moveup"> <div class="ttypography"><p>Here is my thinking about this problem, which is much easier to understand: Lets say we need T seconds to make array becoming non descending. On each seconds from 1 to T we can choose any set of numbers from array to add 2^(t-1). It means that for each element of the array, on each second, we have choice to add or not to add this power of 2. So it means we can choose ANY number to add to each of array element. So the question is now simple: what is the min number M so that if for each a[i] we choose some number from 0 up to M to add to it, we can make array non descending. I just go from left to right, if next a[i+1] is less than a[i] I increase it to be equal a[i].</p></div> </div> </div> <div class="reply info"> <a class="comment-602492 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602492 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602492"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602531" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602531" href="?#comment-602531" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602531" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602531"> <div class="moveup"> <div class="ttypography"><p>why do we need to add the 1?</p></div> </div> </div> <div class="reply info"> <a class="comment-602531 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602531 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602531"> <li> <div class="comment"> <table class="comment-table" commentId="602549" commentParentId="602531"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602549" href="?#comment-602549" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602531" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602549" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602549"> <div class="moveup"> <div class="ttypography"><p>because suppose the highest bit is 2 that will be 100 but the time this would have occurred will be 3 seconds(1,2,4). Due to this, we need to add 1 to the highest bit that we obtain.</p></div> </div> </div> <div class="reply info"> <a class="comment-602549 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602549 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602549"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602429" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602429" href="?#comment-602429" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602429" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602429" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602429"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain how the answer of this testcase in problem div2/probC is 3.</p><p>4 2 -1 -3 -4</p></div> </div> </div> <div class="reply info"> <a class="comment-602429 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602429 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602429"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602431" href="?#comment-602431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602431" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602431"> <div class="moveup"> <div class="ttypography"><p>For DIV2D, first root the tree at any leaf (here, leaf = vertex with degree 1), and note that the XOR sum along any root leaf path must be 0. Now, delete all the leaves and the edges that lead from the leaves to their parents. In this graph, to get maximum value of f, assign distinct powers of 2 to each edge. Then re-introduce the leaves and leaf-to-parent edges, and assign them weights such that XOR sum from root to leaf will be zero. Notice that the values assigned to these leaf-to-parent edges will be distinct unless two leaves share the same parents. Thus, the maximum value of f will be n — 1 — (lvs — p), where lvs = number of leaves in this tree and p = number of nodes which have exactly one child leaf.</p><p>To get minimum f, do the same thing above (root tree at any leaf, then delete leaves and all leaf-parent edges). Then, in this new graph, assign weight 2 to the edge incident on the root, and to all other edges assign weight 1. Now, reintroduce the leaves and the leaf-parent edges, and assign these edges weights such that XOR sum along the root leaf path is 0. Notice that you will only have to assign weights of either 2 or 3 to these edges. So f &lt;= 3. The only case left is to work out when f = 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602431"> <li> <div class="comment"> <table class="comment-table" commentId="602644" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zass" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zass" title="Expert zass" class="rated-user user-blue">zass</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602644" href="?#comment-602644" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602644" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="916405" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602644"> <div class="moveup"> <div class="ttypography"><p>In lvs is root considered one of the leaves and in p is the parent of the root considered as one among p when the parent of root only has root as its child?</p></div> </div> </div> <div class="reply info"> <a class="comment-602644 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602644 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602644"> <li> <div class="comment"> <table class="comment-table" commentId="602811" commentParentId="602644"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602811" href="?#comment-602811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602644" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602811" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602811"> <div class="moveup"> <div class="ttypography"><p>In lvs, the root is not considered one of the leaves. And in p, parent of root is not included because root does not have a parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-602811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602811"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602798" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 18:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602798" href="?#comment-602798" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602798" class="CommentVoteFrame" data-commentRating="5" 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;">+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-602798"> <div class="moveup"> <div class="ttypography"><p>Nice explanation but I read your code to understand fully. =)) Code is still the best explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-602798 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602798 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602798"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="650339" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rmaa" style="position: relative;"> <img src='https://userpic.codeforces.org/499170/avatar/6e864314e460334e.jpg'/> </a> <div><a href="/profile/rmaa" title="Expert rmaa" class="rated-user user-blue">rmaa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2020 23:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-650339" href="?#comment-650339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="650339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="499170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-650339"> <div class="moveup"> <div class="ttypography"><p>Thanks so much, your explanation helped me understand this problem 2 months later! :) It's so mind-boggling to understand how one can come up with this construction in time during the contest.</p><p>The reason I want to post here is to add something to your solution in case anyone after me has the same question. (also to just solidify my own understanding) I actually had this question myself while reading — we know that the XOR from the root to all the different leaves must be zero. But how can one prove that the XOR from one leaf to another is also zero? (a path that does not include the root, but rather just two leaves in the tree?) After all we need to make EVERY path between leaves XOR to 0</p><p>The logic is quite simple. As we said before we know XOR of the paths from the root to the two leafs, call them L1 and L2, are both zero. These paths must share some similar segment (specifically its from the LCA(L1, L2) to the root). Call the XOR of this shared segment X. Then we know the XOR from the path from L1 to LCA(L1, L2) = X, and same with the path from L2 to LCA(L1, L2). Because if (x XOR y) = 0, then x = y, and the XOR of the whole path can be broken up the XOR of two segments L1 -&gt; LCA, LCA -&gt; root. (same with L2).</p><p>The editorial also explains this logic a bit but I hope what I wrote can help. </p></div> </div> </div> <div class="reply info"> <a class="comment-650339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-650339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-650339"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602484" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602484" href="?#comment-602484" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602484" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602484" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602484"> <div class="moveup"> <div class="ttypography"><p>I cant understand the editorial of Powered Addition clearly.Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-602484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602484"> <li> <div class="comment"> <table class="comment-table" commentId="602493" commentParentId="602484"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602493" href="?#comment-602493" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602493" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602493"> <div class="moveup"> <div class="ttypography"><p>I just post my 2 cents above, hope it is easier to understand</p></div> </div> </div> <div class="reply info"> <a class="comment-602493 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602493 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602493"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602629" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ZeroNik" style="position: relative;"> <img src='https://userpic.codeforces.org/1336702/avatar/4935627333ab6d15.jpg'/> </a> <div><a href="/profile/ZeroNik" title="Pupil ZeroNik" class="rated-user user-green">ZeroNik</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602629" href="?#comment-602629" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602629" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1336702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602629"> <div class="moveup"> <div class="ttypography"><p>Who can explain problem A again. I don't undersatand why answer is n</p></div> </div> </div> <div class="reply info"> <a class="comment-602629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602629"> <li> <div class="comment"> <table class="comment-table" commentId="602636" commentParentId="602629"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/invincibel31" style="position: relative;"> <img src='https://userpic.codeforces.org/842069/avatar/78296878ae951a3.jpg'/> </a> <div><a href="/profile/invincibel31" title="Expert invincibel31" class="rated-user user-blue">invincibel31</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602636" href="?#comment-602636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602629" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="842069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602636"> <div class="moveup"> <div class="ttypography"><p>ans is equal to n bcz of the vertically standing diamonds in each way there will be only one diamond which would be standing vertically and since the number of diamond in n hence and in n</p></div> </div> </div> <div class="reply info"> <a class="comment-602636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602636"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602791" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hasnaine_" style="position: relative;"> <img src='https://userpic.codeforces.org/553185/avatar/dbae027ec9304551.jpg'/> </a> <div><a href="/profile/Hasnaine_" title="Expert Hasnaine_" class="rated-user user-blue">Hasnaine_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602791" href="?#comment-602791" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602791" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="553185" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602791"> <div class="moveup"> <div class="ttypography"><p><strong>Problem Div1(C), Div2(E):</strong> </p><p>Can anyone please elaborate on why this combination on bitmasking works?</p><p>Or, how to prove this combination works?</p><p>Thanks in advance. </p></div> </div> </div> <div class="reply info"> <a class="comment-602791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602791"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RedSnowstorm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RedSnowstorm" title="Expert RedSnowstorm" class="rated-user user-blue">RedSnowstorm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602796" href="?#comment-602796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602796" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="789793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602796"> <div class="moveup"> <div class="ttypography"><p>Could someone please elaborate a bit more on Div1 C ? I understand the solution up to the first picture, but I don't understand neither the meaning of the second picture nor the rest of the solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602796"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602873" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ateev_mishra7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ateev_mishra7" title="Pupil ateev_mishra7" class="rated-user user-green">ateev_mishra7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602873" href="?#comment-602873" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602873" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174913" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602873"> <div class="moveup"> <div class="ttypography"><p>Why does my solution to Div2-C is not working . <a href="https://codeforces.com/contest/1339/submission/76407068">https://codeforces.com/contest/1339/submission/76407068</a></p><p>can somebody please help me out on this .</p></div> </div> </div> <div class="reply info"> <a class="comment-602873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602873"> <li> <div class="comment"> <table class="comment-table" commentId="603718" commentParentId="602873"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603718" href="?#comment-603718" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603718" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603718" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603718"> <div class="moveup"> <div class="ttypography"><p>Well let's take the sequence as 1 4 1 4, your code outputs 3 while it is supposed to output 2 since you can add 1 and 2 to the third element and get a sorted output.</p></div> </div> </div> <div class="reply info"> <a class="comment-603718 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603718 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603718"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="603291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vyush" style="position: relative;"> <img src='https://userpic.codeforces.org/814106/avatar/d2c40519525d0732.jpg'/> </a> <div><a href="/profile/Vyush" title="Expert Vyush" class="rated-user user-blue">Vyush</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603291" href="?#comment-603291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603291" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603291" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603291"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain division1C/division2E I am not able to understand the approach in the editorial.I got the nim product observation but I don't know how to implement it also i don't get the editorials approach.If anyone could help that would be great.Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-603291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604316" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sheaf" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sheaf" title="Expert sheaf" class="rated-user user-blue">sheaf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 19:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604316" href="?#comment-604316" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604316" 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="604316" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="509827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604316"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, as for Div1E, isn't $$$R=in(P)\cap Q$$$, instead it is $$$R=in(V)\cap Q$$$? The latter just doesn't make sense if you consider the lemma 3. $$$in(V)$$$ is the subset of all vertices that have at least one outgoing edge, $$$in(P)\cap Q$$$ is the subset of all vertices of $$$Q$$$ that have at least one outgoing edge. Then lemma 3, which says there are edges from set $$$S$$$ to $$$R$$$, can't be true because it says that $$$S$$$ — a subset of $$$Q$$$ without outgoing edges — has edges pointing to $$$R$$$. On contrary, if we set $$$R=in(P)\cap Q$$$ we, can prove lemma 3 by forbidding the configuration from the statement. Also, can't really prove part of lemma 4 that says that $$$R$$$ has no cycles without it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604316 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604316 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604316"> <li> <div class="comment"> <table class="comment-table" commentId="604403" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604403" href="?#comment-604403" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604403" 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="604403" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604403"> <div class="moveup"> <div class="ttypography"><p>(erased)</p></div> </div> </div> <div class="reply info"> <a class="comment-604403 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604403 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604403"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604580" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 01:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604580" href="?#comment-604580" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604580" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604580" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604580"> <div class="moveup"> <div class="ttypography"><p>oops, sorry, I understood your comment wrong. To be honest, I don't fully understand approach of this problem, so I would like to call author of this problem directly. <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></p></div> </div> </div> <div class="reply info"> <a class="comment-604580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604580"> <li> <div class="comment"> <table class="comment-table" commentId="604593" commentParentId="604580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604593" href="?#comment-604593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604593" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604593"> <div class="moveup"> <div class="ttypography"><p>Ugh, bad boy. You should be more responsible to your round.</p></div> </div> </div> <div class="reply info"> <a class="comment-604593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604593"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604591" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604591" href="?#comment-604591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604591" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604591"> <div class="moveup"> <div class="ttypography"><p>Oh, I didn't realise that I used the variable $$$V$$$ 2 times. Now I fixed it. When I said $$$in(V) \cap Q$$$ I refered to the $$$V$$$ in Lemma 2. Thanks for pointinh out my mistake.</p></div> </div> </div> <div class="reply info"> <a class="comment-604591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604591"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604631" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 07:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604631" href="?#comment-604631" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604631"> <div class="moveup"> <div class="ttypography"><p>Hi, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, how does observation 1 of edge weight problem work since the shape of tree is determined by input rather than can be arbitrary constructed as in observation 1? Take example input 3 for instance. Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-604631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604631"> <li> <div class="comment"> <table class="comment-table" commentId="604757" commentParentId="604631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604757" href="?#comment-604757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604757" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604757"> <div class="moveup"> <div class="ttypography"><p><img alt="ex1" src="/predownloaded/a2/a8/a2a877e5c47802fc77cb6bee8965a15f80b6e799.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You can see that we can make $$$f = 1$$$ in this tree anyway.</p></div> </div> </div> <div class="reply info"> <a class="comment-604757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604757"> <li> <div class="comment"> <table class="comment-table" commentId="605625" commentParentId="604757"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605625" href="?#comment-605625" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604757" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605625" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605625"> <div class="moveup"> <div class="ttypography"><p>I must misunderstand your meaning, but doesn't f=2 in the graph since there are weight of 1 and 2?</p><p>Or do you mean that the edge on 7-4-3 could be equivalent to a single edge with weight of 3=weight(7,4) xor weight(4,3)=2 xor 1? Thus in this way the observation 1 can be applied?</p></div> </div> </div> <div class="reply info"> <a class="comment-605625 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605625 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605625"> <li> <div class="comment"> <table class="comment-table" commentId="605631" commentParentId="605625"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605631" href="?#comment-605631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605625" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605631"> <div class="moveup"> <div class="ttypography"><p>This picture shows how you can manage $$$f \le 3$$$ in this tree with first observation. By &quot; <em>You can see that we can make $$$f = 1$$$ in this tree any</em> &quot; I mean you can replace all weights $$$2$$$ to $$$1$$$ to make $$$f = 1$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-605631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605631"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/karanbhatia116" style="position: relative;"> <img src='https://userpic.codeforces.org/872128/avatar/afb324a25af3a491.jpg'/> </a> <div><a href="/profile/karanbhatia116" title="Newbie karanbhatia116" class="rated-user user-gray">karanbhatia116</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604739" href="?#comment-604739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872128" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604739"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain me the second test case for Div1A/Div2C(<a href="/contest/1338/problem/A" title="Codeforces Round 633 (Div. 1)">1338A - Powered Addition</a>)?</p> <pre><code>Input: 6 3 1000000000 0 -1000000000 1 6 2 -1000000000 1000000000 2 1000000000 -1000000000 2 1000000000 1000000000 2 -1000000000 -1000000000 Output: 31 0 0 31 0 0 </code></pre><p>How is the output 31 and not 32? If it is 31 then we must have added 2^30 in 0 and -1000000000 but that does not make the array non-decreasing in the first test case.</p></div> </div> </div> <div class="reply info"> <a class="comment-604739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604739"> <li> <div class="comment"> <table class="comment-table" commentId="604760" commentParentId="604739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 12:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604760" href="?#comment-604760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604760" 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="604760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604760"> <div class="moveup"> <div class="ttypography"><p>Select $$$2$$$-nd index at last second only, and $$$3$$$-rd index all the time. Then you get </p><p>$$$a = [10^{9}, 0, -10^{9}] \to [10^{9}, 0 + 2^{30}, -10^{9} + 2^{0} + 2^{1} + \ldots + 2^{30}] = [1000000000, 1073741824, 1147483647]$$$</p><p>So you can make $$$a$$$ non-decreasing in $$$31$$$ seconds.</p></div> </div> </div> <div class="reply info"> <a class="comment-604760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604760"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605553" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 09:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605553" href="?#comment-605553" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605553" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605553"> <div class="moveup"> <div class="ttypography"><p>why does the answer for div2-C depends only on largest difference? Can someone explain in detailed manner i am unable to get the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-605553 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605553 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605553"> <li> <div class="comment"> <table class="comment-table" commentId="605637" commentParentId="605553"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605637" href="?#comment-605637" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605553" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605637" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605637" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605637"> <div class="moveup"> <div class="ttypography"><p>Fact 1: $$$2^{0} + 2^{1} + \ldots + 2^{t-1} \lt 2^{t}$$$.</p><p>This means if you want to add something equal or bigger than $$$2^{t}$$$ on some position, then you should use more than $$$t$$$ seconds.</p><p>Fact 2: Required seconds is determined by maximum bit of difference.</p><p>From two facts you can observe that smaller difference leads to shorter time.</p><p>I will write few examples below;</p> <ul> <li>diff = 0 -&gt; 0 second</li> <li>diff = 1 -&gt; 1 second ($$$1 = 2^{0}$$$)</li> <li>diff = 2 -&gt; 2 seconds ($$$2 = 2^{1}$$$)</li> <li>diff = 3 -&gt; 2 seconds ($$$3 = 2^{0} + 2^{1}$$$)</li> <li>diff = 4 -&gt; 3 seconds ($$$4 = 2^{2}$$$)</li> <li>diff = 5 -&gt; 3 seconds ($$$5 = 2^{0} + 2^{2}$$$)</li> <li>diff = 6 -&gt; 3 seconds ($$$6 = 2^{1} + 2^{2}$$$)</li> <li>diff = 7 -&gt; 3 seconds ($$$7 = 2^{0} + 2^{1} + 2^{2}$$$)</li> <li>...</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-605637 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605637 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605637"> <li> <div class="comment"> <table class="comment-table" commentId="605676" commentParentId="605637"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 12:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605676" href="?#comment-605676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605637" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605676"> <div class="moveup"> <div class="ttypography"><p>Thank you for your explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-605676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605676"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605607" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anshul23" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anshul23" title="Expert anshul23" class="rated-user user-blue">anshul23</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 10:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605607" href="?#comment-605607" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605607" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="551535" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-605607"> <div class="moveup"> <div class="ttypography"><p>Nice editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-605607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605607"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grapo_Oranges" style="position: relative;"> <img src='https://userpic.codeforces.org/1443313/avatar/3242fe30f43d5e9f.jpg'/> </a> <div><a href="/profile/grapo_Oranges" title="Expert grapo_Oranges" class="rated-user user-blue">grapo_Oranges</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 13:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605691" href="?#comment-605691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605691" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605691"> <div class="moveup"> <div class="ttypography"><p>@Anyone who solved Div2. D during the contest, can you explain how did you actually figure out the solution and was there any specific problem you ever did in past that helped you to solve this problem?</p></div> </div> </div> <div class="reply info"> <a class="comment-605691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606212" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ankit_12" style="position: relative;"> <img src='https://userpic.codeforces.org/1461518/avatar/2c0c3df83d1920d2.jpg'/> </a> <div><a href="/profile/Ankit_12" title="Pupil Ankit_12" class="rated-user user-green">Ankit_12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 10:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606212" href="?#comment-606212" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="606212" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="606212" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1461518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606212"> <div class="moveup"> <div class="ttypography"><p>Why this sequence is not correct for n=9, A/C to question Perfect Triples please Any one Help???</p><p>9 : 1 2 3 4 3 7 8 4 12</p></div> </div> </div> <div class="reply info"> <a class="comment-606212 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606212 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606212"> <li> <div class="comment"> <table class="comment-table" commentId="606260" commentParentId="606212"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 13:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606260" href="?#comment-606260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606212" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606260"> <div class="moveup"> <div class="ttypography"><p>Because $$$3$$$ is used twice in your sequence.</p></div> </div> </div> <div class="reply info"> <a class="comment-606260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606260"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606777" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/striver_79" style="position: relative;"> <img src='https://userpic.codeforces.org/584222/avatar/92d0d608686eabcc.jpg'/> </a> <div><a href="/profile/striver_79" title="Candidate Master striver_79" class="rated-user user-violet">striver_79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 13:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606777" href="?#comment-606777" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606777" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="584222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606777"> <div class="moveup"> <div class="ttypography"><p>Video editorial for <a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div2D</a>/<a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div1B</a>: </p></div> </div> </div> <div class="reply info"> <a class="comment-606777 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606777 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606777"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607351" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/richikchanda1999" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/richikchanda1999" title="Pupil richikchanda1999" class="rated-user user-green">richikchanda1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 18:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607351" href="?#comment-607351" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607351" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="510979" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607351"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces,</p><p>Can anyone help me to come up with a better approach to the excluded problem (<a href="https://codeforces.com/gym/276159/problem/D1A_old">https://codeforces.com/gym/276159/problem/D1A_old</a>) apart from the brute-force approach which is giving TLE?</p></div> </div> </div> <div class="reply info"> <a class="comment-607351 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607351 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607351"> <li> <div class="comment"> <table class="comment-table" commentId="608851" commentParentId="607351"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/22/2020 18:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-608851" href="?#comment-608851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607351" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="608851" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="608851" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-608851"> <div class="moveup"> <div class="ttypography"><p>$$$x \oplus (x \cdot 2^{30}) = x \cdot (1 + 2^{30})$$$ if $$$x &lt; 2^{30}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-608851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-608851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-608851"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="619618" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/10/2020 21:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-619618" href="?#comment-619618" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="619618" 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="619618" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-619618"> <div class="moveup"> <div class="ttypography"><p>After a few weeks when I want to solve the problems I just realized the Editorial is so beautiful, those well-illustrated pictures and interesting stories made the Editorial so great!</p><p>But I had problems solving D1E. I cannot figure out why the <strong>Lemma 3</strong> and <strong>Lemma 6a/b</strong> are correct (And of course the final observations). Can you give proofs for them?</p><p><strong>UPD: After asking others, now I understood. Anyway, thanks the great Editorial!</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-619618 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-619618 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-619618"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="620074" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/11/2020 17:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620074" href="?#comment-620074" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="620074" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620074"> <div class="moveup"> <div class="ttypography"><p>i found a crazy solution of div1B <a href="https://codeforces.com/contest/1338/submission/76346806">https://codeforces.com/contest/1338/submission/76346806</a> can anyone plz explain the logic</p></div> </div> </div> <div class="reply info"> <a class="comment-620074 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620074 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620074"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="630800" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shpvb" style="position: relative;"> <img src='https://userpic.codeforces.org/720608/avatar/3fa49fe2fc134d7b.jpg'/> </a> <div><a href="/profile/shpvb" title="Candidate Master shpvb" class="rated-user user-violet">shpvb</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/27/2020 13:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-630800" href="?#comment-630800" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="630800" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-630800"> <div class="moveup"> <div class="ttypography"><p>Can someone provide insight into the mathematical induction referred to in observation 2 of div1C (Perfect Triples)?</p></div> </div> </div> <div class="reply info"> <a class="comment-630800 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-630800 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-630800"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="792521" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Livu_sz" style="position: relative;"> <img src='https://userpic.codeforces.org/1922428/avatar/3153d345afda896c.jpg'/> </a> <div><a href="/profile/Livu_sz" title="Expert Livu_sz" class="rated-user user-blue">Livu_sz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/19/2021 06:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-792521" href="?#comment-792521" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="792521" 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="792521" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1922428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-792521"> <div class="moveup"> <div class="ttypography"><p>B was tough</p></div> </div> </div> <div class="reply info"> <a class="comment-792521 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-792521 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-792521"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1064206" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sartq" style="position: relative;"> <img src='https://userpic.codeforces.org/3093050/avatar/ec7dcd19bb83efab.jpg'/> </a> <div><a href="/profile/sartq" title="Newbie sartq" class="rated-user user-gray">sartq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2023 06:30">5 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1064206" href="?#comment-1064206" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1064206" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="3093050" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1064206"> <div class="moveup"> <div class="ttypography"><p>In div2B can we solve the problem using a hashMap, like storing the values of differences of array and their indexes?</p></div> </div> </div> <div class="reply info"> <a class="comment-1064206 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1064206 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1064206"> </ul> </div> <br/> <div id="editBox-82006" 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 firstPreview82006 = true; var lastPreviewContent82006 = ''; 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=82006] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=82006] 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-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, 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:28:37</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:'81288c53eb1e161c',t:'MTY5NjcwNjkxNy4zNTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1338D
1338
D
ru
D. Вложенные резинки
<div class="problem-statement"><div class="header"><div class="title">D. Вложенные резинки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть дерево из $$$n$$$ вершин. Вы собираетесь преобразовать это дерево в $$$n$$$ резинок на бесконечной плоскости. Должно выполняться следующее;</p><ul> <li> Для каждой пары вершин $$$a$$$ и $$$b$$$, резинки $$$a$$$ и $$$b$$$ должны пересекаться тогда и только тогда, когда между $$$a$$$ и $$$b$$$ в дереве существует ребро. </li><li> Форма резинки должна быть простой петлей. Другими словами, резинка  — это замкнутая кривая без самопересечений. </li></ul><p>Теперь давайте дадим следующие определения: </p><ul> <li> Резинка $$$a$$$ <span class="tex-font-style-bf">включает</span> резинку $$$b$$$, если и только если резинка $$$b$$$ находится полностью внутри резинки $$$a$$$, и они не пересекаются. </li><li> Последовательность резинок $$$a_{1}, a_{2}, \ldots, a_{k}$$$ ($$$k \ge 2$$$) называется <span class="tex-font-style-bf">вложенной</span>, если и только если для всех $$$i$$$ ($$$2 \le i \le k$$$), $$$a_{i-1}$$$ включает в себя $$$a_{i}$$$. </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/344702cbc9dc910c7e10b4dad5c287cabc28d27e.png" style="max-width: 100.0%;max-height: 100.0%;"/> Это пример преобразования. Обратите внимание, что резинки $$$5$$$ и $$$6$$$ являются вложенными. </center><p>Можно доказать, что при заданных ограничениях существует преобразование и последовательность вложенных резинок.</p><p>Какую максимальную длину последовательности вложенных резинок можно получить из данного дерева? Найдите и выведите ее.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$3 \le n \le 10^{5}$$$)  — количество вершин в данном дереве.</p><p>$$$i$$$-я из следующих $$$n-1$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$)  — это означает, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Гарантируется, что данный граф образует дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 3 2 3 3 4 4 5 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 2 3 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно получить вложенную последовательность из $$$4$$$ резинок ($$$1$$$, $$$2$$$, $$$5$$$ и $$$6$$$) с помощью следующего преобразования, приведенного ниже. Конечно, существуют и другие преобразования для создания вложенной последовательности длины $$$4$$$. Однако вы не можете сделать последовательность из $$$5$$$ или более вложенных резинок для данного дерева.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/29a3ee35372e45c994d87155adf2795c5b4600f0.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Одно из возможных преобразований для второго примера приведено ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e8f3a00073f8ac4ef88a3a152423d97d7d9565d7.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="f83680d7507520adacca7a2d0242c962"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="5c85cbb657e064c2cfa3c38de5074b5925e3ec82"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f83680d7507520adacca7a2d0242c962'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1338%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='f83680d7507520adacca7a2d0242c962'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1338">Codeforces Round 633 (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='f83680d7507520adacca7a2d0242c962'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1338/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='f83680d7507520adacca7a2d0242c962'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590534"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f83680d7507520adacca7a2d0242c962'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590534"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10753" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10760" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1338">Задачи</a></li> <li><a href="/contest/1338/submit">Отослать</a></li> <li><a href="/contest/1338/my">Мои посылки</a></li> <li><a href="/contest/1338/status">Статус</a></li> <li><a href="/contest/1338/hacks">Взломы</a></li> <li><a href="/contest/1338/room/1">Комната</a></li> <li><a href="/contest/1338/standings">Положение</a></li> <li><a href="/contest/1338/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8d01701a1afe3b8ff93a00e1befa3fcefc612f69"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Вложенные резинки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть дерево из $$$n$$$ вершин. Вы собираетесь преобразовать это дерево в $$$n$$$ резинок на бесконечной плоскости. Должно выполняться следующее;</p><ul> <li> Для каждой пары вершин $$$a$$$ и $$$b$$$, резинки $$$a$$$ и $$$b$$$ должны пересекаться тогда и только тогда, когда между $$$a$$$ и $$$b$$$ в дереве существует ребро. </li><li> Форма резинки должна быть простой петлей. Другими словами, резинка  — это замкнутая кривая без самопересечений. </li></ul><p>Теперь давайте дадим следующие определения: </p><ul> <li> Резинка $$$a$$$ <span class="tex-font-style-bf">включает</span> резинку $$$b$$$, если и только если резинка $$$b$$$ находится полностью внутри резинки $$$a$$$, и они не пересекаются. </li><li> Последовательность резинок $$$a_{1}, a_{2}, \ldots, a_{k}$$$ ($$$k \ge 2$$$) называется <span class="tex-font-style-bf">вложенной</span>, если и только если для всех $$$i$$$ ($$$2 \le i \le k$$$), $$$a_{i-1}$$$ включает в себя $$$a_{i}$$$. </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/344702cbc9dc910c7e10b4dad5c287cabc28d27e.png" style="max-width: 100.0%;max-height: 100.0%;" /> Это пример преобразования. Обратите внимание, что резинки $$$5$$$ и $$$6$$$ являются вложенными. </center><p>Можно доказать, что при заданных ограничениях существует преобразование и последовательность вложенных резинок.</p><p>Какую максимальную длину последовательности вложенных резинок можно получить из данного дерева? Найдите и выведите ее.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$3 \le n \le 10^{5}$$$)  — количество вершин в данном дереве.</p><p>$$$i$$$-я из следующих $$$n-1$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$)  — это означает, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Гарантируется, что данный граф образует дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 3 2 3 3 4 4 5 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 2 3 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно получить вложенную последовательность из $$$4$$$ резинок ($$$1$$$, $$$2$$$, $$$5$$$ и $$$6$$$) с помощью следующего преобразования, приведенного ниже. Конечно, существуют и другие преобразования для создания вложенной последовательности длины $$$4$$$. Однако вы не можете сделать последовательность из $$$5$$$ или более вложенных резинок для данного дерева.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/29a3ee35372e45c994d87155adf2795c5b4600f0.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Одно из возможных преобразований для второго примера приведено ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e8f3a00073f8ac4ef88a3a152423d97d7d9565d7.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:38</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e059afa7b77',t:'MTY5NjY2NTY5OC4zODMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2700"]
https://codeforces.com/blog/entry/75913
<!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="8bc765f3680682fd8f2decef62cad97d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Codeforces Round #633 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #633 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='8bc765f3680682fd8f2decef62cad97d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F75913">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='8bc765f3680682fd8f2decef62cad97d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:36:25</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:36:25</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='8bc765f3680682fd8f2decef62cad97d'/> <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/McDic">McDic</a></li> <li class="current selectedLava"><a href="/blog/McDic">Blog</a></li> <li><a href="/teams/with/McDic">Teams</a></li> <li><a href="/submissions/McDic">Submissions</a></li> <li><a href="/groups/with/McDic">Groups</a></li> <li><a href="/contests/with/McDic">Contests</a></li> <li><a href="/contests/writer/McDic">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/McDic" style="text-decoration:none;color:black !important;">McDic's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="76444"> <div class="title"> <a href="/blog/entry/75913"> <p>Codeforces Round #633 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a>, <a href="/topic/76444/en2">history</a>, <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p>Hello! I hope all of you enjoyed my contest!</p> <div class="problemTutorial" problemcode="1339A">Tutorial is loading...</div><p><strong>Behind story of A</strong>:</p> <ul> <li>I tried to make the easiest Div2A ever. Will it work? :)</li> </ul> <div class="problemTutorial" problemcode="1339B">Tutorial is loading...</div><p><strong>Behind story of B</strong>:</p> <ul> <li>I tried to block various heuristics. There were some critical heuristics which could pass so many cases. Fortunately I blocked them during testing period, so I hope there won't be much FST this time.</li> </ul> <div class="problemTutorial" problemcode="1338A">Tutorial is loading...</div><p><strong>Behind story of D2C/D1A</strong>:</p> <ul> <li>Originally, there was a different problem for this position. But it used XOR. As I made new D2E/D1C problem, I threw old D2C/D1A away and put this.</li> </ul> <div class="problemTutorial" problemcode="1338B">Tutorial is loading...</div><p><strong>Behind story of D2D/D1B</strong>:</p> <ul> <li>This problem is the most popular problem among testers. I also like this problem a lot.</li> </ul> <div class="problemTutorial" problemcode="1338C">Tutorial is loading...</div><p><strong>Behind story of D2E/D1C</strong>:</p> <ul> <li>Feedback for this problem was too different by testers.</li> <li>I made this problem by modifying <a href="https://codeforces.com/contest/1242/problem/D">Number Discovery</a>, which is one of my previous problems.</li> <li>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this.</li> </ul> <div class="problemTutorial" problemcode="1338D">Tutorial is loading...</div><p><strong>Behind story of D1D</strong>:</p> <ul> <li>This problem was supposed to be D2E at first. But all LGM testers failed this problem during VC, so we thought that this problem's difficulty is high. Meanwhile, I found that old D1D problem can be easily googled, so we removed that problem, push this problem to be D1D, and made another D1C problem. I will share old D1D later.</li> </ul> <div class="problemTutorial" problemcode="1338E">Tutorial is loading...</div><p><strong>Behind story of D1E</strong>:</p> <ul> <li>Thanks <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a> for writing this problem. She is genius in both singing and problemsolving.</li> </ul></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/1338" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 1)</a> </span> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1339" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-88959-76444").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "88959", blogEntryId: "75913", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=mcdic" class="tag notice" style="text-decoration: none;">mcdic</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-76444"><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'>+346</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-76444"><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/McDic"><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/McDic"> McDic </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/75913#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/75913#comments"> 225 </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="82006"> <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 (171)</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="601867" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stefdasca" style="position: relative;"> <img src='https://userpic.codeforces.org/492453/avatar/429fc64e07ff3f4.jpg'/> </a> <div><a href="/profile/stefdasca" title="Candidate Master stefdasca" class="rated-user user-violet">stefdasca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601867" href="?#comment-601867" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601867" 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="601867" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="492453" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601867"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=crOSe84Q6HQ">Video tutorial for div1A/div2C</a></p><p><a href="https://www.youtube.com/watch?v=MMtnJDMM3IE">Video tutorial for div1B/div2D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-601867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601867"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601870" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kerO_o" style="position: relative;"> <img src='https://userpic.codeforces.org/406813/avatar/a505f416e75a37bd.jpg'/> </a> <div><a href="/profile/kerO_o" title="Master kerO_o" class="rated-user user-orange">kerO_o</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601870" href="?#comment-601870" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601870" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="406813" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601870"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-601870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601870"> <li> <div class="comment"> <table class="comment-table" commentId="601963" commentParentId="601870"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601963" href="?#comment-601963" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601963" class="CommentVoteFrame" data-commentRating="30" 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:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601963"> <div class="moveup"> <div class="ttypography"><p>what does this &quot;orz&quot; mean? </p></div> </div> </div> <div class="reply info"> <a class="comment-601963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601963"> <li> <div class="comment"> <table class="comment-table" commentId="602114" commentParentId="601963"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yash18" style="position: relative;"> <img src='https://userpic.codeforces.org/858176/avatar/3cdce86e6de339b8.jpg'/> </a> <div><a href="/profile/yash18" title="Pupil yash18" class="rated-user user-green">yash18</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602114" href="?#comment-602114" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602114" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602114" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="858176" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602114"> <div class="moveup"> <div class="ttypography"><p>Bow down! Bow down to the <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602114 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602114 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602114"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601879" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SkySurfer" style="position: relative;"> <img src='https://userpic.codeforces.org/684272/avatar/41e617735365cc0e.jpg'/> </a> <div><a href="/profile/SkySurfer" title="Specialist SkySurfer" class="rated-user user-cyan">SkySurfer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601879" href="?#comment-601879" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601879" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="684272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601879"> <div class="moveup"> <div class="ttypography"><p>Best Editorial Ever ....Nice Explanation Of both Problems and Solutions . </p></div> </div> </div> <div class="reply info"> <a class="comment-601879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601879"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601890" href="?#comment-601890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601890" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601890" class="CommentVoteFrame" data-commentRating="32" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+32</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601890"> <div class="moveup"> <div class="ttypography"><p>For Div1C, I found out that the nth tuple (an, bn, cn) is basically this: (found via OEIS)</p> <ol> <li><p>an -&gt; nth number with odd number of bits</p></li> <li><p>bn -&gt; nim_multiplcation(2, an) (<a href="https://oeis.org/A006015">https://oeis.org/A006015</a>)</p></li> <li><p>cn = an ^ bn.</p></li> </ol><p>But I was still not able to solve the problem because I didn't know nim multiplication nor did I find any implementation over the net.</p></div> </div> </div> <div class="reply info"> <a class="comment-601890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601890"> <li> <div class="comment"> <table class="comment-table" commentId="601914" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601914" href="?#comment-601914" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601914" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601914"> <div class="moveup"> <div class="ttypography"><p>Nim Arithmetic is definitely overkill for this problem. </p></div> </div> </div> <div class="reply info"> <a class="comment-601914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601914"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="601919" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601919" href="?#comment-601919" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601919" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601919" class="CommentVoteFrame" data-commentRating="71" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+71</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601919"> <div class="moveup"> <div class="ttypography"><p>We found that during testing and thought it wasn't much of an issue exactly because of that, probably you'd spend more time searching about nim multiplication than if you just solved the problem lol</p></div> </div> </div> <div class="reply info"> <a class="comment-601919 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601919 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601919"> <li> <div class="comment"> <table class="comment-table" commentId="601942" commentParentId="601919"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601942" href="?#comment-601942" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601919" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601942" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601942"> <div class="moveup"> <div class="ttypography"><p>Yeah, that is what happened ... I kept on searching for nim multiplcation here and there and wasted too much time. I should have come up with some other approaches ... </p></div> </div> </div> <div class="reply info"> <a class="comment-601942 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601942 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601942"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602731" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602731" href="?#comment-602731" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602731" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602731"> <div class="moveup"> <div class="ttypography"><p>A solution with nim multiplcation: <a href="/contest/1338/submission/76499145" title="Submission 76499145 by amane-ame">76499145</a></p><p>There is no doubt that it is much more complicated than the general solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602731 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602731 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602731"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601893" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Endagorion" style="position: relative;"> <img src='https://userpic.codeforces.org/1643/avatar/5c0b493cf8428ab6.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Endagorion" title="International Grandmaster Endagorion" class="rated-user user-red">Endagorion</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601893" href="?#comment-601893" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601893" class="CommentVoteFrame" data-commentRating="192" data-commentUserId="1643" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+192</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601893"> <div class="moveup"> <div class="ttypography"><p>I don't have proof, but in div1C any triple appears to be $$$(x, x \otimes 2, x \otimes 3)$$$, where $$$\otimes$$$ is nim multiplication.</p></div> </div> </div> <div class="reply info"> <a class="comment-601893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601893"> <li> <div class="comment"> <table class="comment-table" commentId="601983" commentParentId="601893"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601983" href="?#comment-601983" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601983" class="CommentVoteFrame" data-commentRating="64" 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;">+64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601983"> <div class="moveup"> <div class="ttypography"><p>:o</p></div> </div> </div> <div class="reply info"> <a class="comment-601983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601983"> <li> <div class="comment"> <table class="comment-table" commentId="602418" commentParentId="601983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jerry__Jiang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jerry__Jiang" title="Master Jerry__Jiang" class="rated-user user-orange">Jerry__Jiang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602418" href="?#comment-602418" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601983" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602418" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1198521" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602418"> <div class="moveup"> <div class="ttypography"><p>:)</p></div> </div> </div> <div class="reply info"> <a class="comment-602418 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602418 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602418"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601939" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601939" href="?#comment-601939" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601939" 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="601939" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-41" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601939"> <div class="moveup"> <div class="ttypography"><p>[DELETED]</p></div> </div> </div> <div class="reply info"> <a class="comment-601939 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601939 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601939"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prodelta" style="position: relative;"> <img src='https://userpic.codeforces.org/847522/avatar/e144f36263828062.jpg'/> </a> <div><a href="/profile/prodelta" title="Pupil prodelta" class="rated-user user-green">prodelta</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601950" href="?#comment-601950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601950" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="847522" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601950"> <div class="moveup"> <div class="ttypography"><p>System testing is finished , Editorials are out , but my submission for Problem — A still shows Pretests Passed . Link : <a href="https://codeforces.com/contest/1339/submission/76340409">Here</a></p><p>Have I committed some fatal sin for which I am being given such a brutal punishment ?</p><p>What should I do now ?</p></div> </div> </div> <div class="reply info"> <a class="comment-601950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601950"> <li> <div class="comment"> <table class="comment-table" commentId="601964" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shubhammitt" style="position: relative;"> <img src='https://userpic.codeforces.org/785906/avatar/ecb76ca8bc2663f4.jpg'/> </a> <div><a href="/profile/shubhammitt" title="Expert shubhammitt" class="rated-user user-blue">shubhammitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601964" href="?#comment-601964" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601964" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="785906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601964"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-601964 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601964 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601964"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602003" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602003" href="?#comment-602003" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602003" 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-602003"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-602003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602003"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602451" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chidoring" style="position: relative;"> <img src='https://userpic.codeforces.org/1455809/avatar/d62042cde12a7b4e.jpg'/> </a> <div><a href="/profile/chidoring" title="Pupil chidoring" class="rated-user user-green">chidoring</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602451" href="?#comment-602451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602451" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1455809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602451"> <div class="moveup"> <div class="ttypography"><p>rip</p></div> </div> </div> <div class="reply info"> <a class="comment-602451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602451"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601953" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_DynamicCube" style="position: relative;"> <img src='https://userpic.codeforces.org/1381092/avatar/ca9726e93700302b.jpg'/> </a> <div><a href="/profile/_DynamicCube" title="Pupil _DynamicCube" class="rated-user user-green">_DynamicCube</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601953" href="?#comment-601953" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601953" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1381092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601953"> <div class="moveup"> <div class="ttypography"><p>재밌는 문제들 감사합니다! (Thank you for the interesting questions!)</p></div> </div> </div> <div class="reply info"> <a class="comment-601953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601953"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601956" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AceKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AceKing" title="Candidate Master AceKing" class="rated-user user-violet">AceKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601956" href="?#comment-601956" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601956" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="910788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601956"> <div class="moveup"> <div class="ttypography"><p>Fastest editorial I have ever seen!</p></div> </div> </div> <div class="reply info"> <a class="comment-601956 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601956 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601956"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601960" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601960" href="?#comment-601960" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601960" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601960" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601960"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces, I don't have any idea how to approach problems like Div2.D/Div1.B, can someone give me an advice? I am not sure what should I learn first in order to be able to come with a solution to this problem. Thanks :)</p></div> </div> </div> <div class="reply info"> <a class="comment-601960 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601960 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601960"> <li> <div class="comment"> <table class="comment-table" commentId="602364" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 06:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602364" href="?#comment-602364" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602364" class="CommentVoteFrame" data-commentRating="3" 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: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-602364"> <div class="moveup"> <div class="ttypography"><p>From my experience, Div 2 D tends to vary quite bit. I think the best way to go about it is to just keep on practicing a bunch of div 2 D, and look at editorials if you don't quite understand. Also, nice profile picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602364"> <li> <div class="comment"> <table class="comment-table" commentId="602461" commentParentId="602364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602461" href="?#comment-602461" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602364" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602461" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602461" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602461"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, I will keep practicing then :D. PS: I also like your picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602461 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602461 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602461"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602499" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602499" href="?#comment-602499" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602499" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602499"> <div class="moveup"> <div class="ttypography"><p>Well from my experience, it appears atleast one of C/D almost always involves graphs and/or DP. I'd recommend first learning all about graphs, especially some important techniques like DFS, BFS, multi-source BFS, SCC, bridges, cut-vertices etc.[Graphs are really awesome :] Then later move on to DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-602499 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602499 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602499"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604120" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 16:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604120" href="?#comment-604120" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604120" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604120"> <div class="moveup"> <div class="ttypography"><p>IMO you should first learn a little advanced algorithms and data structures and etc., also solve-up contests and past ones, i say the best way is to take virtual contests and then solve the rest of the problems excluding the cases you full the contest :). Also solve Div2.E after the contests, it's fine if you cant solve them, just take your time and try your best then go to editorial and make sure you fully understand the editorial and the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604120"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601962" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601962" href="?#comment-601962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601962" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-118" 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;">-118</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601962"> <div class="moveup"> <div class="ttypography"><p>i think it is better to provide codes instead of stories</p></div> </div> </div> <div class="reply info"> <a class="comment-601962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601962"> <li> <div class="comment"> <table class="comment-table" commentId="601995" commentParentId="601962"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601995" href="?#comment-601995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601995" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601995"> <div class="moveup"> <div class="ttypography"><p>That's why the button showing number of solves next to a problem exists. Click on that and you can see many codes and sort by speed, code length, etc.</p></div> </div> </div> <div class="reply info"> <a class="comment-601995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601995"> <li> <div class="comment"> <table class="comment-table" commentId="601999" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601999" href="?#comment-601999" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601999" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-30" 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;">-30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601999"> <div class="moveup"> <div class="ttypography"><p>I know that, But I want to see the code of the explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-601999 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601999 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601999"> <li> <div class="comment"> <table class="comment-table" commentId="602002" commentParentId="601999"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602002" href="?#comment-602002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601999" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602002" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602002"> <div class="moveup"> <div class="ttypography"><p>Wtf does that mean. Every code is most likely some variation of the explanation if it passed...</p></div> </div> </div> <div class="reply info"> <a class="comment-602002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602002"> <li> <div class="comment"> <table class="comment-table" commentId="602006" commentParentId="602002"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602006" href="?#comment-602006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602002" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602006" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-55" 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;">-55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602006"> <div class="moveup"> <div class="ttypography"><p>No</p></div> </div> </div> <div class="reply info"> <a class="comment-602006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602006"> <li> <div class="comment"> <table class="comment-table" commentId="602113" commentParentId="602006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602113" href="?#comment-602113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602113" class="CommentVoteFrame" data-commentRating="20" 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: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-602113"> <div class="moveup"> <div class="ttypography"><p>Yes</p></div> </div> </div> <div class="reply info"> <a class="comment-602113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602113"> <li> <div class="comment"> <table class="comment-table" commentId="602122" commentParentId="602113"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602122" href="?#comment-602122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602113" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602122" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" 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;">-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-602122"> <div class="moveup"> <div class="ttypography"><p>No is no</p></div> </div> </div> <div class="reply info"> <a class="comment-602122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602122"> <li> <div class="comment"> <table class="comment-table" commentId="602331" commentParentId="602122"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602331" href="?#comment-602331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602331" class="CommentVoteFrame" data-commentRating="41" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602331"> <div class="moveup"> <div class="ttypography"><p>Dumb is dumb</p></div> </div> </div> <div class="reply info"> <a class="comment-602331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602331"> <li> <div class="comment"> <table class="comment-table" commentId="602624" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 15:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602624" href="?#comment-602624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602624" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" 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;">-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-602624"> <div class="moveup"> <div class="ttypography"><p>Who is dumb there?</p></div> </div> </div> <div class="reply info"> <a class="comment-602624 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602624 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602624"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604121" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:02">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604121" href="?#comment-604121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604121" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604121"> <div class="moveup"> <div class="ttypography"><p>BABA IS YOU</p></div> </div> </div> <div class="reply info"> <a class="comment-604121 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604121 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604121"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604142" commentParentId="604121"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604142" href="?#comment-604142" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604142" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604142"> <div class="moveup"> <div class="ttypography"><p>Who is BABA?</p></div> </div> </div> <div class="reply info"> <a class="comment-604142 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604142 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604142"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604648" commentParentId="604142"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Suleyman.A" style="position: relative;"> <img src='https://userpic.codeforces.org/82791/avatar/fc8479c7406b79a3.jpg'/> </a> <div><a href="/profile/Suleyman.A" title="Expert Suleyman.A" class="rated-user user-blue">Suleyman.A</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604648" href="?#comment-604648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604142" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604648" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="82791" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604648"> <div class="moveup"> <div class="ttypography"><p>He is husband of your mother</p></div> </div> </div> <div class="reply info"> <a class="comment-604648 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604648 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604648"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602019" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602019" href="?#comment-602019" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602019" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602019"> <div class="moveup"> <div class="ttypography"><p>Its always better if editorial provides code or snippet about their approach</p></div> </div> </div> <div class="reply info"> <a class="comment-602019 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602019 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602019"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rajiv_kale" style="position: relative;"> <img src='https://userpic.codeforces.org/758545/avatar/575c69bbc5b5a715.jpg'/> </a> <div><a href="/profile/rajiv_kale" title="Newbie rajiv_kale" class="rated-user user-gray">rajiv_kale</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601975" href="?#comment-601975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601975" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601975" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="758545" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601975"> <div class="moveup"> <div class="ttypography"><p>Good editorial. I especially liked those behind stories.</p></div> </div> </div> <div class="reply info"> <a class="comment-601975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601975"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601992" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601992" href="?#comment-601992" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601992" class="CommentVoteFrame" data-commentRating="8" 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;">+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-601992"> <div class="moveup"> <div class="ttypography"><p>My E looks very different, now I'm wondering if it's correct.</p><p>Let's focus only on one big strongly connected component. For each vertex $$$V$$$ all the vertices which point to $$$V$$$ are ordered in a path. So, maybe it's possible to somehow form a cycle from all the vertices from the SCC. Let's take any vertex $$$V$$$. Now, from all the vertices which point to the $$$V$$$ let's take the last one on this path, let's call it $$$U$$$. Fix $$$U$$$ before $$$V$$$ on this cycle. Now, in the same manner, find a vertex that will be before $$$U$$$. And so on until we have a full cycle. My guess is that it's correct and that after this process which vertex points to some interval on the cycle which starts in this vertex. With such a form of the graph, we can easily calculate the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-601992 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601992 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601992"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602013" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602013" href="?#comment-602013" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602013" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-62" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-602013"> <div class="moveup"> <div class="ttypography"><p>Im not gonna lie but div2 was not interesting at all, problems D and E just required some basic observation. I hope future rounds require some more algorithmic skills to solve D and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-602013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602013"> <li> <div class="comment"> <table class="comment-table" commentId="602039" commentParentId="602013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602039" href="?#comment-602039" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602039" class="CommentVoteFrame" data-commentRating="100" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+100</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602039"> <div class="moveup"> <div class="ttypography"><p>How come did you only solve A then?</p></div> </div> </div> <div class="reply info"> <a class="comment-602039 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602039 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602039"> <li> <div class="comment"> <table class="comment-table" commentId="602102" commentParentId="602039"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602102" href="?#comment-602102" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602039" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602102" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-40" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602102"> <div class="moveup"> <div class="ttypography"><p>The point is not how many problems I solved or not but about the quality of problems, pls dont divert issues like this. (btw that submission to A is after contest :p)</p></div> </div> </div> <div class="reply info"> <a class="comment-602102 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602102 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602102"> <li> <div class="comment"> <table class="comment-table" commentId="602128" commentParentId="602102"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602128" href="?#comment-602128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602102" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602128" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602128"> <div class="moveup"> <div class="ttypography"><p>OK, I'm sorry.</p><p>Well, I thought they were good :D. It's kinda subjective. Who's to say &quot;making observations&quot; is worse than &quot;algorithmic skills&quot;? I don't think it's so much about &quot;quality of problems&quot; than &quot;style of problems&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-602128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602128"> <li> <div class="comment"> <table class="comment-table" commentId="602144" commentParentId="602128"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602144" href="?#comment-602144" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602144" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602144"> <div class="moveup"> <div class="ttypography"><p>I agree it's about style problems and I also liked the problems today. However I do agree with <a class="rated-user user-black" href="/profile/bored69" title="Unrated, bored69">bored69</a> that imo too many problems are extremely short to code while relying solely on observation. While I know many people enjoy the short to code problems, it is called _code_forces after all, so I think the solution should be longer than 10 lines to solve the problem, and I would enjoy getting to use some standard algorithms more often as long as the problem is still not straight application</p></div> </div> </div> <div class="reply info"> <a class="comment-602144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602144"> <li> <div class="comment"> <table class="comment-table" commentId="602407" commentParentId="602144"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lessmeaning" style="position: relative;"> <img src='https://userpic.codeforces.org/400632/avatar/4aeb556dedbc357a.jpg'/> </a> <div><a href="/profile/lessmeaning" title="Master lessmeaning" class="rated-user user-orange">lessmeaning</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602407" href="?#comment-602407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602144" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602407" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="400632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602407"> <div class="moveup"> <div class="ttypography"><p>Another Radewoosh's pawn</p></div> </div> </div> <div class="reply info"> <a class="comment-602407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602407"> <li> <div class="comment"> <table class="comment-table" commentId="602903" commentParentId="602407"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602903" href="?#comment-602903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602407" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602903" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602903"> <div class="moveup"> <div class="ttypography"><p>Maybe Radewoosh is my pawn ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-602903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602903"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602017" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602017" href="?#comment-602017" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602017" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602017"> <div class="moveup"> <div class="ttypography"><p>In Div 2-D explanation, I am not able to understand e-l+m part. Can someone help? </p></div> </div> </div> <div class="reply info"> <a class="comment-602017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602017"> <li> <div class="comment"> <table class="comment-table" commentId="602185" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602185" href="?#comment-602185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602185" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602185"> <div class="moveup"> <div class="ttypography"><p>The key construction in the editorial is that for every leaf i, the edge between i and its parent is xor(path(root,parent(i))). This construction guarantees different weights with one exception, what if multiple leaves have same parent? In that case we'll have only one extra distinct weight for all leaves with a common parent. So instead of including weights for all the leaves, we'll include weights only for their parents. Hence, first assume all edges as distinct and include them all(e) , then remove all leaves(l) and finally add those parents (which are non-leaf nodes with atleast one child as leaf (m)). So, we get e-l+m.</p></div> </div> </div> <div class="reply info"> <a class="comment-602185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602185"> <li> <div class="comment"> <table class="comment-table" commentId="602260" commentParentId="602185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602260" href="?#comment-602260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602185" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602260"> <div class="moveup"> <div class="ttypography"><p>I checked your solution. I am having some doubts. 1- Why did you choose your node as the vertex with a maximum degree? 2- The minimum f condition says if only odd paths are there, the minimum f is 1. forex. like 1--2--3--4(-- is an edge), how only one number can ensure bitwise XOR of 0?</p></div> </div> </div> <div class="reply info"> <a class="comment-602260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602260"> <li> <div class="comment"> <table class="comment-table" commentId="602286" commentParentId="602260"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602286" href="?#comment-602286" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602260" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602286" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602286"> <div class="moveup"> <div class="ttypography"><ol> <li>I had a different approach when I started coding, so i start with that node with maximum degre. In my approach, the necessary condition is that root node should not be leaf, if it is I'll not count one leaf in my dfs leading to a wrong answer.</li> <li>Minimum condition for f is, all leaf nodes should be at a distance of same parity from root, so that every pair of leaves are separated by even no. Of edges.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-602286 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602286 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602286"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602209" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602209" href="?#comment-602209" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602209" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602209"> <div class="moveup"> <div class="ttypography"><p>What about the case when edges with same weight are counted twice? In the picture Observation 3, the edges (1)-(2) and (2)-(6) should have the same weight. But the formula will count them as separate weights. Can someone please explain&gt;</p></div> </div> </div> <div class="reply info"> <a class="comment-602209 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602209 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602209"> <li> <div class="comment"> <table class="comment-table" commentId="602232" commentParentId="602209"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:52">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602232" href="?#comment-602232" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602209" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602232" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602232"> <div class="moveup"> <div class="ttypography"><p>No, it won't be counted twice. edges 1-2 and 2-6 are first removed by subtracting l (e-l) and then added once for their common parent 2(non-leaf node with 2 leaves) through m (e-l+m)</p></div> </div> </div> <div class="reply info"> <a class="comment-602232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602232"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602029" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaaven" style="position: relative;"> <img src='https://userpic.codeforces.org/851917/avatar/442eaf7f5f3f896b.jpg'/> </a> <div><a href="/profile/vaaven" title="Master vaaven" class="rated-user user-orange">vaaven</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602029" href="?#comment-602029" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602029" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="851917" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602029"> <div class="moveup"> <div class="ttypography"><p>Thank you for interesting and hard problems, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a>!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-602029 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602029 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602029"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602042" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602042" href="?#comment-602042" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602042" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602042" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602042"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1338/problem/B" title="Codeforces Round 633 (Div. 1)">1338B - Edge Weight Assignment</a> Dont get it how the construction works at all. Should't there be some recursion as we do a dfs? How/where do we start, and what to do in &quot;each step&quot;, assuming there are steps?</p></div> </div> </div> <div class="reply info"> <a class="comment-602042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602042"> <li> <div class="comment"> <table class="comment-table" commentId="602203" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AdsT" style="position: relative;"> <img src='https://userpic.codeforces.org/639570/avatar/f12b9c2694f9e204.jpg'/> </a> <div><a href="/profile/AdsT" title="Expert AdsT" class="rated-user user-blue">AdsT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602203" href="?#comment-602203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602203" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="639570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602203"> <div class="moveup"> <div class="ttypography"><p>I agree, everyone seemed to have just done the same thing, take one from the back and one from the front, I just am not able to prove this. How do I come to this conclusion?</p></div> </div> </div> <div class="reply info"> <a class="comment-602203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602203"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602348" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602348" href="?#comment-602348" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602348" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602348"> <div class="moveup"> <div class="ttypography"><p>This is a way that I came up with to always satisfy 3 distinct colors for every tree.</p><p>Choose a leaf (called $$$u$$$) and choose the connected node with this leaf (called $$$r$$$ and obviously this node won't be a leaf, as $$$n &gt;= 3$$$) as the root.</p><p>What we are going to construct is we are trying to make: $$$ xor(path(r, v)) = xor(path(r, u)) $$$ for every leaf $$$v$$$. Because when $$$ xor(path(r, v)) = xor(path(r, u)) $$$ then $$$ xor(path(r, v_1)) = xor(path(r, v_2)) ( = xor(path(r, u)))$$$ for every pair of leaves.</p><p>We have $$$xor(path(r, v_1)) = xor(path(r, v_2)) $$$ $$$\Leftrightarrow (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_1))) = (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_2)))$$$ $$$\Leftrightarrow xor(path(lca(v_1, v_2), v_1)) = xor(path(lca(v_1, v_2), v_2)) \Rightarrow$$$ Satisfy the condition</p><p>So here is what I do:</p> <ol> <li>Let the edge between $$$r$$$ and $$$u$$$ have weight $$$1$$$.</li> <li>We dfs from $$$r$$$, save the prefix $$$xor$$$ value from $$$r$$$ to the node $$$p$$$ we are at and dfs to node children $$$v$$$ of $$$p$$$:</li> </ol> <ul> <li>If $$$v$$$ is a leaf, then we need to assign this edge so that the prefix $$$xor$$$ value will be equal to $$$1$$$ ($$$ = xor(path(r, u))$$$).</li> <li>If $$$v$$$ is not a leaf, then we assign $$$2$$$ to that edge. Why? Because we need to get rid of the case when the prefix $$$xor$$$ value at node $$$p$$$ (parent of leaf $$$v$$$, for example) is equal to $$$1$$$ ($$$ = xor(path(r, u))$$$) and whatever we assign $$$edge(p, v)$$$ we cannot make the prefix $$$xor$$$ value at leaf $$$v$$$ equal to $$$1$$$ anymore.</li> </ul><p>P/s: Ask me anything that you may not understand ^^. </p></div> </div> </div> <div class="reply info"> <a class="comment-602348 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602348 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602348"> <li> <div class="comment"> <table class="comment-table" commentId="602440" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602440" href="?#comment-602440" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602440" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602440"> <div class="moveup"> <div class="ttypography"><p>Thanks!</p><p>Now I think the key observation to come up with all of this is the parity of distances of three leafs.</p><p>$$$parity(dist(l1,l2)) \oplus parity(dist(l1,l3)) = parity(dist(l2,l3))$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-602440 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602440 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602440"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603442" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603442" href="?#comment-603442" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603442" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603442"> <div class="moveup"> <div class="ttypography"><p>I didnt get the part where you assign 2 to the edge that is not a leaf.</p></div> </div> </div> <div class="reply info"> <a class="comment-603442 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603442 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603442"> <li> <div class="comment"> <table class="comment-table" commentId="603446" commentParentId="603442"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603446" href="?#comment-603446" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603442" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603446"> <div class="moveup"> <div class="ttypography"><p>Consider all the edges which not connect any leaf are assigned $$$2$$$, then all the prefix $$$xor$$$ value at node $$$p$$$ (not a leaf) will be either $$$...000$$$ or $$$...010$$$. So when we go to a leaf we can assign a possible value to make the prefix $$$xor$$$ equal to $$$...001$$$. </p><p>Suppose we don't assign $$$2$$$ but $$$1$$$ or $$$3$$$ then there will be the case when at node $$$p$$$ (not a leaf but have a leaf child) the prefix $$$xor$$$ may be $$$...001$$$ and go to node $$$v$$$ (the leaf child of $$$p$$$) whether we assign the edge $$$1$$$, $$$2$$$ or $$$3$$$ then the prefix $$$xor$$$ can't be $$$...001$$$ anymore.</p><p>Sorry for my bad English !</p></div> </div> </div> <div class="reply info"> <a class="comment-603446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603446"> <li> <div class="comment"> <table class="comment-table" commentId="603451" commentParentId="603446"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603451" href="?#comment-603451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603446" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603451" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603451"> <div class="moveup"> <div class="ttypography"><p>Thanks to your quick reply,I am able to understand it.Can you please suggest some resources or something that would help me in solving problem cause' I am only able to solve upto problem c everytime?</p></div> </div> </div> <div class="reply info"> <a class="comment-603451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603451"> <li> <div class="comment"> <table class="comment-table" commentId="603456" commentParentId="603451"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603456" href="?#comment-603456" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603451" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603456" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603456"> <div class="moveup"> <div class="ttypography"><p>My suggestions: Solve problems and reflect upon what you have done wrong ... or what's observation you missed (And note them back obviously) ... or new algorithms (search and read for them and do 3 — 5 problems about that topic). Sometimes algorithm have signs, try to see that.</p><p>P/s: It's my own opinion anyway. Good luck &lt;3.</p></div> </div> </div> <div class="reply info"> <a class="comment-603456 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603456 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603456"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606855" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Darooha" style="position: relative;"> <img src='https://userpic.codeforces.org/27157/avatar/c4be2a4212ec87ed.jpg'/> </a> <div><a href="/profile/Darooha" title="Pupil Darooha" class="rated-user user-green">Darooha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606855" href="?#comment-606855" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606855" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="27157" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-606855"> <div class="moveup"> <div class="ttypography"><p>To everybody: The editorial has this update. It makes the problem much simpler:</p><p>(Update) There is an another way to approach, provided by Darooha.</p><p>If you label vertices instead of edges where all leaves have same label and none of neighbors have same label, then you can consider edge weight as xor of two vertices' labels, so this is basically equivalent to original problem.</p><p>Now for minimum, you can see that labelling 0 to leaves, and 1,2 to non-leaves are enough, so you can prove minimum value of f is at most 3. In same manner, you can try parity checking to check if f value can be 1 or not.</p><p>For maximum, assign 0 to all leaves and assign all different values(21,22,...) to non-leaf vertices, then you can see all edge weights(except leaves connected to same vertex) are different.</p></div> </div> </div> <div class="reply info"> <a class="comment-606855 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606855 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606855"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rojansudev700" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rojansudev700" title="Newbie rojansudev700" class="rated-user user-gray">rojansudev700</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602066" href="?#comment-602066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1236502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602066"> <div class="moveup"> <div class="ttypography"><p>Can anybody please explain problem A and its editorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-602066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602066"> <li> <div class="comment"> <table class="comment-table" commentId="602098" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602098" href="?#comment-602098" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602098"> <div class="moveup"> <div class="ttypography"><p>You may refer to the picture in the editorial. In this picture, if you put the red one in, you will find there is only one way to fill it( also described in the picture). Hence, since there are N different ways for putting the red one in, the answer is simply N.</p></div> </div> </div> <div class="reply info"> <a class="comment-602098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602098"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602157" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Apr/12/2020 21:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602157" href="?#comment-602157" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602157" 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-602157"> <div class="moveup"> <div class="ttypography"><p>Consider you want to find the answer for shape with size N. Let's say you put a Vertical diamond initially then places of all other diamonds are decided. So this is 1 way to put diamonds.</p><p>The other way is to put two horizontal diamonds on top left and bottom left and then we are have to find ways to puts diamonds in a shape of size N-1.</p><p>Ans(i) = 1 + Ans(i-1) <br /> {1 for the way in which vertical diamond is placed on the leftmost position}</p><p>Ans(i) = 1 + Ans(i-1) = i, given ans(1) =1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602157"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602093" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bayweiheng" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bayweiheng" title="Grandmaster bayweiheng" class="rated-user user-red">bayweiheng</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602093" href="?#comment-602093" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602093" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="533715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602093"> <div class="moveup"> <div class="ttypography"><p>In Div1E, How can we calculate the contribution from vertices with no indegree? If v has no indegree, then dis(u,v) is known but how do we find dis(v,u)? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-602093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602093"> <li> <div class="comment"> <table class="comment-table" commentId="602110" commentParentId="602093"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602110" href="?#comment-602110" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602093" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602110" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602110"> <div class="moveup"> <div class="ttypography"><p>If $$$u$$$ has no in-degree then $$$dis(u,v)=1, dis(v,u)=614n$$$ for all $$$u\neq v$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602110 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602110 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602110"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602145" href="?#comment-602145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602145" 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="602145" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602145"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">E intuition?</b><div class="spoiler-content" style="display: none;"><p>Assume that all nodes have positive in-degree. Then we can arrange the nodes in a cycle $$$c_0,c_1,\ldots, c_{n-1}$$$ such that $$$c_i$$$ has edges to $$$c_{i+1},c_{i+2},\ldots,c_{(i+out(i))\pmod{n}}$$$ where $$$out(i)$$$ denotes the out-degree of node $$$c_i$$$. To find this cycle, start with any vertex $$$x$$$ and topologically sort $$$in(x)$$$. Then repeat with the last node of $$$in(x)$$$ (with respect to the sorted order).</p><p>For all $$$i$$$, $$$out(i)&gt;0$$$ and $$$out(i)\le out((i+1)\pmod{n})+1$$$. Suppose that $$$i&lt;j$$$. Then $$$out(i)+i\le out(j)+j$$$ and the distance from $$$c_j$$$ to $$$c_i$$$ is three iff $$$out(i)+i=out(j)+j$$$. Otherwise, it's one or two.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-602145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602145"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602151" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misqwerty" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/misqwerty" title="Newbie misqwerty" class="rated-user user-gray">misqwerty</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602151" href="?#comment-602151" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602151" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="727011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602151"> <div class="moveup"> <div class="ttypography"><p>Do anyone else other than me recognize this submission as a hack for a hack and there were two successful hacking attempts. That's a <strong>cheat</strong>. <a href="/contest/1339/submission/76401969" title="Submission 76401969 by SIBshaan">76401969</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602151 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602151 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602151"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602165" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602165" href="?#comment-602165" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602165" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602165"> <div class="moveup"> <div class="ttypography"><p>how to find editorial in english for Atcoder Begginer contest 162 on their website it's in japanese..</p></div> </div> </div> <div class="reply info"> <a class="comment-602165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602165"> <li> <div class="comment"> <table class="comment-table" commentId="602170" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:39">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602170" href="?#comment-602170" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602170" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602170"> <div class="moveup"> <div class="ttypography"><p>Pay attention to the red line written on the first page of the Japanese editorial .</p></div> </div> </div> <div class="reply info"> <a class="comment-602170 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602170 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602170"> <li> <div class="comment"> <table class="comment-table" commentId="602195" commentParentId="602170"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602195" href="?#comment-602195" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602170" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602195" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602195"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602195 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602195 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602195"> <li> <div class="comment"> <table class="comment-table" commentId="602248" commentParentId="602195"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602248" href="?#comment-602248" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602195" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602248" 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-602248"> <div class="moveup"> <div class="ttypography"><p>I've solved A,B,C,D if you want, i can tell u how to solve them</p></div> </div> </div> <div class="reply info"> <a class="comment-602248 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602248 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602248"> <li> <div class="comment"> <table class="comment-table" commentId="602255" commentParentId="602248"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602255" href="?#comment-602255" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602248" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602255" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602255" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602255"> <div class="moveup"> <div class="ttypography"><p>please tell me how you solved D</p></div> </div> </div> <div class="reply info"> <a class="comment-602255 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602255 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602255"> <li> <div class="comment"> <table class="comment-table" commentId="602270" commentParentId="602255"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602270" href="?#comment-602270" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602255" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602270" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602270" 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-602270"> <div class="moveup"> <div class="ttypography"><p>So you gonna fix i and k such that S[i] != S[k]. So in the range [i + 1, k — 1] you should find the number of characters C different from S[i] as well as S[j]. So, for example, if S[i] = 'R' and S[k] = 'G', C = 'B'. So these different characters can be found using segment tree, maybe there is other method too. Also you should check for the second condition, if (k — i) % 2 == 0 and S[(i + k) / 2] == c, you gonna decrement that number by one.</p></div> </div> </div> <div class="reply info"> <a class="comment-602270 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602270 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602270"> <li> <div class="comment"> <table class="comment-table" commentId="602272" commentParentId="602270"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602272" href="?#comment-602272" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602270" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602272" 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-602272"> <div class="moveup"> <div class="ttypography"><p>That's my solution, but I think there is a better solution described in the following video: <a href="https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s">https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602272"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602172" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602172" href="?#comment-602172" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602172" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602172"> <div class="moveup"> <div class="ttypography"><p>Btw, why ask this here xD</p></div> </div> </div> <div class="reply info"> <a class="comment-602172 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602172 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602172"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602167" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602167" href="?#comment-602167" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602167" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602167"> <div class="moveup"> <div class="ttypography"><p>Could someone elaborate a bit more the intuition behind Div1D and how to implement it?</p></div> </div> </div> <div class="reply info"> <a class="comment-602167 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602167 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602167"> <li> <div class="comment"> <table class="comment-table" commentId="602265" commentParentId="602167"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602265" href="?#comment-602265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602167" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602265" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602265" class="CommentVoteFrame" data-commentRating="42" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+42</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602265"> <div class="moveup"> <div class="ttypography"><p>I approached this problem by considering what happens if we only consider the minimum connected subgraph containing the answer, where the answer is the set of nodes $$$S$$$ that form the nested rubber bands. First, consider each $$$v\in S$$$ as a circle, so we have $$$|S|$$$ nested circles. The other vertices of this minimum connected subgraph must contribute to connecting two or more circles, and we can consider them as line segments. </p><p>Colour the line segments red and the circles blue. Then, we'll see that the red vertices lie on a path, because we can trace out a path in this alternate representation of the tree. Furthermore, the blue vertices form an independent set, and each is adjacent to at least one red vertex.</p><p>DP states:</p><p>For each state, I suppose that the red vertices lie on a path in the subtree rooted at u with one endpoint at u.</p> <ul> <li><p>take[u] = number of blue vertices if u is blue</p></li> <li><p>skip[u] = number of blue vertices if u is red</p></li> </ul><p>DP transitions:</p> <ul> <li><p><code>take[u] = max(1 + skip[child])</code>. Since we're interested in a path, we take the max.</p></li> <li><p><code>skip[u] = max(#children-1 + max(take[child], skip[child]))</code>. If we colour u red, then we can colour all its uncoloured neighbours blue, but we still want to be able to choose for the next node in the path.</p></li> </ul><p>To get the answer, consider a path rooted at u. We need to know the best two values of <code>take[child]</code> and <code>max(take[child], skip[child])</code> to find the answer for such a path.</p><p>I'm sure you could fit the dp and get the solution in one dfs function, but here's my rather long and verbose code: <a href="https://codeforces.com/contest/1338/submission/76420228">https://codeforces.com/contest/1338/submission/76420228</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602265"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602182" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gouravmajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1380497/avatar/470f8f4adfac9b5d.jpg'/> </a> <div><a href="/profile/gouravmajee" title="Newbie gouravmajee" class="rated-user user-gray">gouravmajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602182" href="?#comment-602182" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602182" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1380497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602182"> <div class="moveup"> <div class="ttypography"><p>this was my first contest :) I passed question 1. </p></div> </div> </div> <div class="reply info"> <a class="comment-602182 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602182 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602182"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602191" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aid" style="position: relative;"> <img src='https://userpic.codeforces.org/106240/avatar/ab90218e19d9e731.jpg'/> </a> <div><a href="/profile/aid" title="International Grandmaster aid" class="rated-user user-red">aid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602191" href="?#comment-602191" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602191" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="106240" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602191"> <div class="moveup"> <div class="ttypography"><p>$$$O(n^2\log(n))$$$ can be squeezed in E: <a href="/contest/1338/submission/76419686" title="Submission 76419686 by aid">76419686</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-602191 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602191 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602191"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602210" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cdc.biobot" style="position: relative;"> <img src='https://userpic.codeforces.org/152957/avatar/23e3d83914fae0f6.jpg'/> </a> <div><a href="/profile/cdc.biobot" title="Newbie cdc.biobot" class="rated-user user-gray">cdc.biobot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602210" href="?#comment-602210" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602210" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602210" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="152957" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602210"> <div class="moveup"> <div class="ttypography"><p>I beg your pardon, but I think problem statement of div2A should have been a bit clearer in explaining the term 'covering differently'. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-602210 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602210 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602210"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602211" href="?#comment-602211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602211" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602211"> <div class="moveup"> <div class="ttypography"><p>In Div2 D for finding the maximum f value, what is the proof that there is no other construction possible that can possibly have more distinct weights? For example, consider a tree with the non-leaf nodes having degree 4. In the observation 3 picture, we can add to node 2, a replica structure of its child node 3. That will make node 2's degree 4. How to prove for this case(and in general) that the maximum value of f will not exceed e-l+m?</p></div> </div> </div> <div class="reply info"> <a class="comment-602211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602211"> <li> <div class="comment"> <table class="comment-table" commentId="602241" commentParentId="602211"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602241" href="?#comment-602241" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602211" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602241" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602241"> <div class="moveup"> <div class="ttypography"><p>Because that's the upper bound of the value.</p><p>Every edge that isn't adjacent to a leaf doesn't matter. Edges for leaves that are adjacent to the same non-leaf vertex need to be equal. That can be counted as in the editorial because — (leaves — non-leaf vertex adjacent to a leaf) is exactly the number of edges to leaves that are free to receive values.</p></div> </div> </div> <div class="reply info"> <a class="comment-602241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602241"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602221" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602221" href="?#comment-602221" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602221" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602221"> <div class="moveup"> <div class="ttypography"><p>hi..what is the maximum time in which it's good to solve div2 — A and B.. because i'm practicing only DIV2 A and B question in virtual contest..and still took more than 1 h to solve both...some time i failed to solve B.. Thanks in advance..</p></div> </div> </div> <div class="reply info"> <a class="comment-602221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602221"> <li> <div class="comment"> <table class="comment-table" commentId="602497" commentParentId="602221"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602497" href="?#comment-602497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602221" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602497"> <div class="moveup"> <div class="ttypography"><p>See this round was tough, but I think top coders take max 15 min for both, at my rating I think even 30 mins would be fine and for you, 45-60 min is the max you should ideally take</p></div> </div> </div> <div class="reply info"> <a class="comment-602497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602497"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602236" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Muhammad98" style="position: relative;"> <img src='https://userpic.codeforces.org/697747/avatar/2c13087bfd195af6.jpg'/> </a> <div><a href="/profile/Muhammad98" title="Specialist Muhammad98" class="rated-user user-cyan">Muhammad98</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602236" href="?#comment-602236" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="697747" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602236"> <div class="moveup"> <div class="ttypography"><p>The only Div2A that I couldn't solve during the round XD</p></div> </div> </div> <div class="reply info"> <a class="comment-602236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602236"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602238" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602238" href="?#comment-602238" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602238" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602238"> <div class="moveup"> <div class="ttypography"><p>Nice editorial and pictures! <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> One suggestion: It'll be easier to read d1E if you use lowercase letters for vertices and upper case letters for sets.</p></div> </div> </div> <div class="reply info"> <a class="comment-602238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602238"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gjaiswal108" style="position: relative;"> <img src='https://userpic.codeforces.org/756634/avatar/f398cd162ff7d60f.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/gjaiswal108" title="Expert gjaiswal108" class="rated-user user-blue">gjaiswal108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602251" href="?#comment-602251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602251" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756634" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602251"> <div class="moveup"> <div class="ttypography"><p><code>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this</code></p><p>Can anyone tell me what is meaning of OEIS in the story of D2E ?</p></div> </div> </div> <div class="reply info"> <a class="comment-602251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602251"> <li> <div class="comment"> <table class="comment-table" commentId="602259" commentParentId="602251"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/blitzitout" style="position: relative;"> <img src='https://userpic.codeforces.org/505681/avatar/39b2976ffc156007.jpg'/> </a> <div><a href="/profile/blitzitout" title="Expert blitzitout" class="rated-user user-blue">blitzitout</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602259" href="?#comment-602259" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602251" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602259" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602259" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="505681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602259"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/">This</a> is where you can find insights/recurrences of random sequences.</p></div> </div> </div> <div class="reply info"> <a class="comment-602259 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602259 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602259"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602252" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T-REXX" style="position: relative;"> <img src='https://userpic.codeforces.org/455170/avatar/f7f08af680e3156f.jpg'/> </a> <div><a href="/profile/T-REXX" title="Pupil T-REXX" class="rated-user user-green">T-REXX</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602252" href="?#comment-602252" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602252" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="455170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602252"> <div class="moveup"> <div class="ttypography"><p>I tried solving div2C by iterating through the array, whenever a[i]&gt;a[i+1] I added to all j=i+1 and j&lt;n lowest power of 2 possible to make it a[i]&lt;=a[i+1]. Lowest power was calculated using a vector of powers of 2. But it does not work, and I am unable to find out why. Can anyone help?</p></div> </div> </div> <div class="reply info"> <a class="comment-602252 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602252 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602252"> <li> <div class="comment"> <table class="comment-table" commentId="602471" commentParentId="602252"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bryceShakeair" style="position: relative;"> <img src='https://userpic.codeforces.org/872528/avatar/f8595cfd5dbfc474.jpg'/> </a> <div><a href="/profile/bryceShakeair" title="Specialist bryceShakeair" class="rated-user user-cyan">bryceShakeair</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602471" href="?#comment-602471" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602252" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602471" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872528" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602471"> <div class="moveup"> <div class="ttypography"><p>try 1 0 1 0 1 0 The optimal answer is x = 1 i.e. select indexes 2 , 4 ,6 you get 1 1 1 1 1 1 I hope that is clear </p></div> </div> </div> <div class="reply info"> <a class="comment-602471 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602471 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602471"> <li> <div class="comment"> <table class="comment-table" commentId="604684" commentParentId="602471"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604684" href="?#comment-604684" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602471" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604684" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604684"> <div class="moveup"> <div class="ttypography"><p>Thanks. </p></div> </div> </div> <div class="reply info"> <a class="comment-604684 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604684 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604684"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602282" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant_raja" style="position: relative;"> <img src='https://userpic.codeforces.org/742080/avatar/101f3740a4030218.jpg'/> </a> <div><a href="/profile/nishant_raja" title="Pupil nishant_raja" class="rated-user user-green">nishant_raja</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602282" href="?#comment-602282" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602282" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742080" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602282"> <div class="moveup"> <div class="ttypography"><p>Can anyone briefly explain the problem &quot;Powered Addition&quot;, I mean full approach and walk through an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-602282 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602282 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602282"> <li> <div class="comment"> <table class="comment-table" commentId="602498" commentParentId="602282"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jbs1jbs1jbs1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/jbs1jbs1jbs1" title="Specialist jbs1jbs1jbs1" class="rated-user user-cyan">jbs1jbs1jbs1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602498" href="?#comment-602498" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602282" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602498" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602498"> <div class="moveup"> <div class="ttypography"><p>My approach was as follows:</p><p>Let's say that the list is <code>[1, 7, 6, 5]</code>. We go through and we look at all the pairs <code>(a[i], a[i+1])</code>. We start with <code>(1,7)</code>. It satisfies the property of being non-decreasing, so we do nothing. Next, we go to <code>(7, 6)</code>. <code>6 &lt; 7</code>, meaning we have to add something to &quot;6&quot; to make it bigger. I assert (and will explain below the reason why), that it is possible and optimal to convert the &quot;6&quot; into a &quot;7&quot;. The list then becomes <code>[1, 7, 7, 5]</code>. Next, we look at the final pair <code>(7, 5)</code> and do the same: convert the &quot;5&quot; to a &quot;7&quot;, so that the final list becomes [1, 7, 7, 7].</p><p>When we convert a pair (a, b) to the pair (a, a), it means that we need to add some quantity (a-b) to it. If that quantity is 18, for example, then we can do this with 16 + 2 = 2^4 + 2^1. If that quantity is 15, we can do this with 2^0 + 2^1 + 2^2 + 2^3. In general, there is exactly one way to do the addition of distinct powers of 2 to get from one number to another.</p><p>You can find out which powers of 2 you need to add together by converting the difference into binary. The definition of binary is that where there is a &quot;1&quot; you can add the relevant power of 2.</p><p>In any case, I'm just saying that it is always <strong>possible</strong> to do this, and it doesn't matter what the exact powers of 2 are, you just need to know what the biggest power of 2 needed will be. This is because if you're using a bigger power of 2, for example 2^5, it means that seconds 1, 2, 3, 4, 5, 6 have already happened, so you could have, in the past, added 2^0, 2^1, 2^2, 2^3, 2^4 if you needed to do so.</p><p>The biggest power of 2 needed can be worked out by taking the logarithm base 2 of the difference, and then rounding down.</p><p>The code would then be something like this:</p> <pre><code>max_power_found = -1 for i in range(len(a) - 1): if a[i + 1] &lt; a[i]: difference = a[i] - a[i + 1] biggest_power = floor(log2(difference)) max_power_found = max(max_power_found, biggest_power) a[i + 1] = a[i] print(max_power_found + 1) </code></pre><p>Note that I initialise <code>max_power_found</code> to <code>-1</code> so that at the end, if nothing has happened because the array was already non-decreasing, it becomes <code>0</code> when you add 1.</p><p>Note also that even though we don't need to output the final array, I have the line <code>a[i + 1] = a[i]</code>. This is because the next pair needs to know about the change we just made.</p><p>There are <code>(n-1)</code> possible values of <code>i</code>, and for each one we do some constant time computation (logarithm base 2 is very fast), this is an O(n) solution.</p><p>Note that even if you didn't know about logarithms, you could probably do it very quickly because log2(10^5) is very small (though I haven't tested to make sure this doesn't TLE):</p> <pre><code>def biggest_power_needed(difference): # Outputs -1 if difference is 0. answer = -1 total = 0 while total &lt; difference: answer++ total += pow(2, answer) if total == difference: return answer else: return answer - 1 </code></pre><p>Again, we do <code>answer - 1</code> because we can use the smaller powers of 2 to increase it to exactly equal the difference.</p></div> </div> </div> <div class="reply info"> <a class="comment-602498 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602498 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602498"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shivamsaluja20" style="position: relative;"> <img src='https://userpic.codeforces.org/820036/avatar/92e6360dd7bc5c3d.jpg'/> </a> <div><a href="/profile/shivamsaluja20" title="Specialist shivamsaluja20" class="rated-user user-cyan">shivamsaluja20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602291" href="?#comment-602291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602291" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="820036" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602291"> <div class="moveup"> <div class="ttypography"><p>For the first time for problem A, it took me around 50 minutes to figure out and ironically that was the easiest one liner solution possible. Take the input and print it xD.</p></div> </div> </div> <div class="reply info"> <a class="comment-602291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EleCursity" style="position: relative;"> <img src='https://userpic.codeforces.org/388600/avatar/c667ca12cb3a5eb2.jpg'/> </a> <div><a href="/profile/EleCursity" title="Expert EleCursity" class="rated-user user-blue">EleCursity</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602292" href="?#comment-602292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602292" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="388600" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602292"> <div class="moveup"> <div class="ttypography"><p>Nice Editorial and nice problems. In <strong>div2E/div1C</strong> .I've found a strange pattern for the bits in the n-th triple . but I can't manage to code it during the contest. this is my code <a href="/contest/1339/submission/76432679" title="Submission 76432679 by EleCursity">76432679</a> .</p></div> </div> </div> <div class="reply info"> <a class="comment-602292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602297" href="?#comment-602297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602297"> <div class="moveup"> <div class="ttypography"><p>2D, I understand nothing, damn constructive problems and damn gap between C and D</p><p>&quot;Observation 1. You can prove that minimum value of f is at most 3, by following construction;&quot;</p><p>Well, how do we know there is no other construction where we would have 4 or more?</p><p>&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?</p><p>&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose</p></div> </div> </div> <div class="reply info"> <a class="comment-602297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602297"> <li> <div class="comment"> <table class="comment-table" commentId="602302" commentParentId="602297"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602302" href="?#comment-602302" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602297" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602302" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-602302"> <div class="moveup"> <div class="ttypography"><p>&quot;Well, how do we know there is no other construction where we would have 4 or more?&quot; The problem is asking for the minimum, there is a construction where $$$3$$$ is possible so the minimum is never greater than $$$3$$$</p><p>&quot;&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?&quot; Because we decided that that's how the construction should look like. Another example of a construction which would work is edges connecting a leaf having a weight of $$$2$$$ or $$$3$$$ depending on the parity leaf's depth and all other edges having a weight of $$$1$$$.</p><p>&quot;&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose&quot; Here's a proof: Notice that we can consider each bit separately and then an assignment works if the condition is satisfied for all bits. Let's say we choose numbers $$$a$$$ and $$$b$$$. If both $$$a$$$ and $$$b$$$ have some bit set to $$$1$$$ then that is the same as the $$$f=1$$$ case. If there is no bit which both $$$a$$$ and $$$b$$$ have set to 1 then that means that there is a bit which $$$a$$$ has set to $$$1$$$ and $$$b$$$ has set to $$$0$$$ and that there is a bit which $$$a$$$ has set to $$$0$$$ and $$$b$$$ has set to $$$1$$$, so each path needs to have an even number of both $$$a$$$ and $$$b$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602302 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602302 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602302"> <li> <div class="comment"> <table class="comment-table" commentId="602304" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 02:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602304" href="?#comment-602304" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602304" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602304"> <div class="moveup"> <div class="ttypography"><p>1-2) Oh, so it was about describing a generic technique of assigning values, not about the specific tree on the picture. Then it makes more sense</p><p>3) The confusing part here was that I thought it was about the number of a and b in the whole tree, not on the requested path, and didn't understand why.</p><p>I'll reread it with this in mind</p><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602304"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603392" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 02:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603392" href="?#comment-603392" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603392" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603392" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603392"> <div class="moveup"> <div class="ttypography"><p>I've got how we come up with f=3 from the comments</p><p>However I still don't understand the same part in the editorial &quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>On the picture we have a string of non-leaves, all of which have degree 3. And all the leaves obviously have degree 1 So following this statement we're supposed to have the same weights for every edge connecting a non-leaf to a leaf on the picture. However, this is not the case. </p></div> </div> </div> <div class="reply info"> <a class="comment-603392 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603392 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603392"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/feecIe6418" style="position: relative;"> <img src='https://userpic.codeforces.org/699680/avatar/da9b3b3e29a8fe7b.jpg'/> </a> <div><a href="/profile/feecIe6418" title="International Grandmaster feecIe6418" class="rated-user user-red">feecIe6418</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 03:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602320" href="?#comment-602320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602320" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="699680" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602320"> <div class="moveup"> <div class="ttypography"><p>Finally become master in this round. I like the problems! Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-602320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602334" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602334" href="?#comment-602334" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602334" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602334"> <div class="moveup"> <div class="ttypography"><p><strong>HELP! Please</strong></p><p>Hi, everyone! My friends has some trouble in his solutions, He has submitted this solution <a href="/contest/1339/submission/76367506" title="Submission 76367506 by zhouxiaolun">76367506</a> during the round, However, after the system pending test, He did not get an AC, but still the Pretest passed. The score for this problem was not added to my friends. He has submitted totally the same code just now, <a href="/contest/1339/submission/76438866" title="Submission 76438866 by zhouxiaolun">76438866</a>, and get an AC. Why did this happen? It has effected on my friends ratings, Where can I find the administor to solve the trouble? (sorry for my poor english)</p></div> </div> </div> <div class="reply info"> <a class="comment-602334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602334"> <li> <div class="comment"> <table class="comment-table" commentId="602339" commentParentId="602334"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iynaur87" style="position: relative;"> <img src='https://userpic.codeforces.org/561459/avatar/4516a52f8c97c0c2.jpg'/> </a> <div><a href="/profile/iynaur87" title="Candidate Master iynaur87" class="rated-user user-violet">iynaur87</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602339" href="?#comment-602339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602334" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602339" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="561459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602339"> <div class="moveup"> <div class="ttypography"><p>Weired. You can Send a message to <a href="https://codeforces.com/profile/MikeMirzayanov">https://codeforces.com/profile/MikeMirzayanov</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602339"> <li> <div class="comment"> <table class="comment-table" commentId="602345" commentParentId="602339"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602345" href="?#comment-602345" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602339" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602345" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602345"> <div class="moveup"> <div class="ttypography"><p>Thank you! You are so kind!</p></div> </div> </div> <div class="reply info"> <a class="comment-602345 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602345 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602345"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602341" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Raghu150999" style="position: relative;"> <img src='https://userpic.codeforces.org/714738/avatar/992860969ab6c84.jpg'/> </a> <div><a href="/profile/Raghu150999" title="Expert Raghu150999" class="rated-user user-blue">Raghu150999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602341" href="?#comment-602341" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602341" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714738" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602341"> <div class="moveup"> <div class="ttypography"><p>Great editorial. Thanks a lot!</p></div> </div> </div> <div class="reply info"> <a class="comment-602341 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602341 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602341"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602383" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aspiriner" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/aspiriner" title="Expert aspiriner" class="rated-user user-blue">aspiriner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602383" href="?#comment-602383" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602383" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1393907" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602383"> <div class="moveup"> <div class="ttypography"><p>in the div 2 B </p><p>i do not understand what the 'Sort the list, and make an oscillation centered on middle element like picture below.' means.</p><p>i just dont know how to sort it and what should i do in the next step.</p><p>please help me!</p></div> </div> </div> <div class="reply info"> <a class="comment-602383 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602383 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602383"> <li> <div class="comment"> <table class="comment-table" commentId="602411" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shisuko" style="position: relative;"> <img src='https://userpic.codeforces.org/554313/avatar/42772b63e4542d29.jpg'/> </a> <div><a href="/profile/Shisuko" title="Candidate Master Shisuko" class="rated-user user-violet">Shisuko</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602411" href="?#comment-602411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602411" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="554313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602411"> <div class="moveup"> <div class="ttypography"><p>Sort the elements in ascending order. Then you go smallest-&gt;largest-&gt;second smallest-&gt;second largest... and so on. If you draw it on paper, you can see that the gaps are always getting smaller because it's a subset of the previous gap.</p></div> </div> </div> <div class="reply info"> <a class="comment-602411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602411"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602415" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602415" href="?#comment-602415" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602415" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602415"> <div class="moveup"> <div class="ttypography"><p>Imagine the problem is the same, but differences between pairs must be non increasing instead of non decreasing ( | a_ i — a_i-1 | &gt;= | a_i-1 — a_i-2 | ). If we solve this, we can just reverse the answer and we will get an answer to the original problem. </p><p>Now, imagine we start with the biggest element to the left. What number should we add next to maximize their difference? The smallest element. So we add it. After that, what number not yet added would maximize the difference of the pair? The second biggest element, and it is not hard to see it will be smaller or equal than the first pair. If we continue to do this, we can get an answer.</p><p>So to build it we just sort the initial array and then build it in the following way: a[N] , a[1] , a[N-1] , a[2] , a[N-2] , a[3] ... </p><p>After this, don't forget to reverse the answer to solve the original problem. </p><p>Submission: <a href="/contest/1339/submission/76418078" title="Submission 76418078 by Diegogrc">76418078</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602415 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602415 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602415"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602445" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xD." style="position: relative;"> <img src='https://userpic.codeforces.org/918251/avatar/298a43e5c9cee8f5.jpg'/> </a> <div><a href="/profile/xD." title="Pupil xD." class="rated-user user-green">xD.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602445" href="?#comment-602445" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602445" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602445" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="918251" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602445"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/aspiriner" title="Pupil aspiriner">aspiriner</a> <strong>This picture may help you</strong> <img alt=" " src="/predownloaded/43/9a/439a03f6fa84e1a1c14509dbd3d5c4c88ee8d5a3.php" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-602445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602445"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602386" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misty1999" style="position: relative;"> <img src='https://userpic.codeforces.org/461973/avatar/bda2e09a046c8571.jpg'/> </a> <div><a href="/profile/misty1999" title="Specialist misty1999" class="rated-user user-cyan">misty1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602386" href="?#comment-602386" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602386" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="461973" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602386"> <div class="moveup"> <div class="ttypography"><p>First I thought maximal independent set in div1D, but got Wrong Answer on pretest 4.</p></div> </div> </div> <div class="reply info"> <a class="comment-602386 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602386 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602386"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuber_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/820815/avatar/9d558886908a602d.jpg'/> </a> <div><a href="/profile/cuber_coder" title="Master cuber_coder" class="rated-user user-orange">cuber_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602400" href="?#comment-602400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602400" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="820815" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602400"> <div class="moveup"> <div class="ttypography"><p>Great problemset, a beautifully written editorial, no queueforces, strong pretests and quick system testing makes it a wonderful round! Hope to participate in more rounds authored by you in future!</p><p>P.S. : my most special round till date since I finally reached CM !</p></div> </div> </div> <div class="reply info"> <a class="comment-602400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602400"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602404" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602404" href="?#comment-602404" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602404" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602404"> <div class="moveup"> <div class="ttypography"><p>can someone explain div2-C,i am not able to understand the editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-602404 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602404 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602404"> <li> <div class="comment"> <table class="comment-table" commentId="602437" commentParentId="602404"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602437" href="?#comment-602437" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602404" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602437" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602437"> <div class="moveup"> <div class="ttypography"><p>first of all find the max difference between any two number (O(n)). then you just need to count number of digits in it. which can be done using log2 of that difference. note: ceil function is to be used for ex: 2.5 would be rounded off to 3.</p><p>here's my code(which is actually someone else but I copied it and modified a little, but is self explanatory )</p><p><a href="https://codeforces.com/contest/1339/submission/76446573">https://codeforces.com/contest/1339/submission/76446573</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602437 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602437 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602437"> <li> <div class="comment"> <table class="comment-table" commentId="602494" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602494" href="?#comment-602494" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602494" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602494"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/FinalBoss_" title="Pupil FinalBoss_">FinalBoss_</a> Can you please explain why did you add 1 in log2(dis+1) ?</p><p>I guess dis is the max number required to add.Why +1 ?My first submission was same but i didnt add 1 it got wa.</p></div> </div> </div> <div class="reply info"> <a class="comment-602494 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602494 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602494"> <li> <div class="comment"> <table class="comment-table" commentId="602546" commentParentId="602494"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602546" href="?#comment-602546" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602494" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602546" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602546"> <div class="moveup"> <div class="ttypography"><p>yes dis is the max number required to add. log2(dis+1) is done because... we were asked to find 2^(x-1).</p><p>in case all numbers are equal and dis is 0 or if array is already increasing and dis is still 0, then log(0) becomes undefined. Now since we don't need actual value but ceiling of it so adding 1 to dis and then taking log will have same effect but also it will remove ambiguity of log(0).</p></div> </div> </div> <div class="reply info"> <a class="comment-602546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602546"> <li> <div class="comment"> <table class="comment-table" commentId="602650" commentParentId="602546"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602650" href="?#comment-602650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602546" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602650"> <div class="moveup"> <div class="ttypography"><p>Thanks, got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-602650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602650"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603609" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaibhavsingh100070" style="position: relative;"> <img src='https://userpic.codeforces.org/792197/avatar/6a8b6f989cc93e7d.jpg'/> </a> <div><a href="/profile/vaibhavsingh100070" title="Pupil vaibhavsingh100070" class="rated-user user-green">vaibhavsingh100070</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 09:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603609" href="?#comment-603609" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603609" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="792197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603609"> <div class="moveup"> <div class="ttypography"><p>Can you please explain for this test case n = 5 a = [ 1, 2, 1, 4, 1] For this output is ** 2**. How in 2 steps we will make this array non decreasing?</p></div> </div> </div> <div class="reply info"> <a class="comment-603609 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603609 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603609"> <li> <div class="comment"> <table class="comment-table" commentId="604681" commentParentId="603609"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604681" href="?#comment-604681" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603609" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604681" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604681" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604681"> <div class="moveup"> <div class="ttypography"><p>Same doubt. Hoping someone to answer.</p><p>Edit: Got it. Should have read the question carefully. It says select any indices not continuous indices.</p><p>for n=5 ans array [ 1 2 1 4 1 ] </p><p>Step 1: Select indices : Select 3 and 5 ( begins from 0) Step 2: Increase by 1 then by 2 ( 2^x-1 , put x=1 and then 2) So array becomes : 1 2 4 4 4 which is non-decreasing.</p></div> </div> </div> <div class="reply info"> <a class="comment-604681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604681"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602409" href="?#comment-602409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602409" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602409"> <div class="moveup"> <div class="ttypography"><p>I have doubt in 1339 B -Sorted Adjacent Differences: If the array is: -2 5 5 6 The answer will be 5 -2 5 6 which is wrong Please explain if i am wrong</p></div> </div> </div> <div class="reply info"> <a class="comment-602409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602409"> <li> <div class="comment"> <table class="comment-table" commentId="602428" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602428" href="?#comment-602428" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602428"> <div class="moveup"> <div class="ttypography"><p>it is wrong because the required condition is not fulfilled as your answer will make seqeunce like this 7&lt;=7&gt;1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602428"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602433" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mestu" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mestu" title="Expert Mestu" class="rated-user user-blue">Mestu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602433" href="?#comment-602433" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602433" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="922247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602433"> <div class="moveup"> <div class="ttypography"><p>For array -2 5 5 6 the answer will be 5 5 -2 6 </p></div> </div> </div> <div class="reply info"> <a class="comment-602433 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602433 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602433"> <li> <div class="comment"> <table class="comment-table" commentId="602473" commentParentId="602433"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602473" href="?#comment-602473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602433" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602473"> <div class="moveup"> <div class="ttypography"><p>yes,but according to tutorial it is printing 5-2 5 6</p></div> </div> </div> <div class="reply info"> <a class="comment-602473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602473"> <li> <div class="comment"> <table class="comment-table" commentId="602740" commentParentId="602473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602740" href="?#comment-602740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602740"> <div class="moveup"> <div class="ttypography"><p>according to tutorial it will print 5 5 -2 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-602740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602740"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602427" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/inazuma_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/inazuma_11" title="Newbie inazuma_11" class="rated-user user-gray">inazuma_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602427" href="?#comment-602427" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602427" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1335781" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602427"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain O(N) approach for div 2C ? I know how to do it in O(NlogN) but not in O(N)</p></div> </div> </div> <div class="reply info"> <a class="comment-602427 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602427 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602427"> <li> <div class="comment"> <table class="comment-table" commentId="602432" commentParentId="602427"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602432" href="?#comment-602432" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602427" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602432" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602432"> <div class="moveup"> <div class="ttypography"><p>While traversing the array keep a count of what maximum difference have you seen so far from the previous element i.e maximum value uptil that i minus the array value at that i. Then once you found the maximum difference than going for finding the position of the highest bit in this maximum difference. The ans is going to be the value of this highest bit + 1. Make sure to include the edge case that if the maximum difference is 0 then the ans is also 0.</p></div> </div> </div> <div class="reply info"> <a class="comment-602432 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602432 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602432"> <li> <div class="comment"> <table class="comment-table" commentId="602492" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602492" href="?#comment-602492" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602492" 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="602492" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602492"> <div class="moveup"> <div class="ttypography"><p>Here is my thinking about this problem, which is much easier to understand: Lets say we need T seconds to make array becoming non descending. On each seconds from 1 to T we can choose any set of numbers from array to add 2^(t-1). It means that for each element of the array, on each second, we have choice to add or not to add this power of 2. So it means we can choose ANY number to add to each of array element. So the question is now simple: what is the min number M so that if for each a[i] we choose some number from 0 up to M to add to it, we can make array non descending. I just go from left to right, if next a[i+1] is less than a[i] I increase it to be equal a[i].</p></div> </div> </div> <div class="reply info"> <a class="comment-602492 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602492 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602492"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602531" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602531" href="?#comment-602531" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602531" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602531"> <div class="moveup"> <div class="ttypography"><p>why do we need to add the 1?</p></div> </div> </div> <div class="reply info"> <a class="comment-602531 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602531 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602531"> <li> <div class="comment"> <table class="comment-table" commentId="602549" commentParentId="602531"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602549" href="?#comment-602549" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602531" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602549" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602549"> <div class="moveup"> <div class="ttypography"><p>because suppose the highest bit is 2 that will be 100 but the time this would have occurred will be 3 seconds(1,2,4). Due to this, we need to add 1 to the highest bit that we obtain.</p></div> </div> </div> <div class="reply info"> <a class="comment-602549 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602549 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602549"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602429" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602429" href="?#comment-602429" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602429" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602429" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602429"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain how the answer of this testcase in problem div2/probC is 3.</p><p>4 2 -1 -3 -4</p></div> </div> </div> <div class="reply info"> <a class="comment-602429 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602429 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602429"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602431" href="?#comment-602431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602431" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602431"> <div class="moveup"> <div class="ttypography"><p>For DIV2D, first root the tree at any leaf (here, leaf = vertex with degree 1), and note that the XOR sum along any root leaf path must be 0. Now, delete all the leaves and the edges that lead from the leaves to their parents. In this graph, to get maximum value of f, assign distinct powers of 2 to each edge. Then re-introduce the leaves and leaf-to-parent edges, and assign them weights such that XOR sum from root to leaf will be zero. Notice that the values assigned to these leaf-to-parent edges will be distinct unless two leaves share the same parents. Thus, the maximum value of f will be n — 1 — (lvs — p), where lvs = number of leaves in this tree and p = number of nodes which have exactly one child leaf.</p><p>To get minimum f, do the same thing above (root tree at any leaf, then delete leaves and all leaf-parent edges). Then, in this new graph, assign weight 2 to the edge incident on the root, and to all other edges assign weight 1. Now, reintroduce the leaves and the leaf-parent edges, and assign these edges weights such that XOR sum along the root leaf path is 0. Notice that you will only have to assign weights of either 2 or 3 to these edges. So f &lt;= 3. The only case left is to work out when f = 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602431"> <li> <div class="comment"> <table class="comment-table" commentId="602644" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zass" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zass" title="Expert zass" class="rated-user user-blue">zass</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602644" href="?#comment-602644" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602644" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="916405" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602644"> <div class="moveup"> <div class="ttypography"><p>In lvs is root considered one of the leaves and in p is the parent of the root considered as one among p when the parent of root only has root as its child?</p></div> </div> </div> <div class="reply info"> <a class="comment-602644 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602644 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602644"> <li> <div class="comment"> <table class="comment-table" commentId="602811" commentParentId="602644"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602811" href="?#comment-602811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602644" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602811" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602811"> <div class="moveup"> <div class="ttypography"><p>In lvs, the root is not considered one of the leaves. And in p, parent of root is not included because root does not have a parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-602811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602811"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602798" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 18:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602798" href="?#comment-602798" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602798" class="CommentVoteFrame" data-commentRating="5" 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;">+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-602798"> <div class="moveup"> <div class="ttypography"><p>Nice explanation but I read your code to understand fully. =)) Code is still the best explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-602798 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602798 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602798"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="650339" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rmaa" style="position: relative;"> <img src='https://userpic.codeforces.org/499170/avatar/6e864314e460334e.jpg'/> </a> <div><a href="/profile/rmaa" title="Expert rmaa" class="rated-user user-blue">rmaa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2020 23:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-650339" href="?#comment-650339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="650339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="499170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-650339"> <div class="moveup"> <div class="ttypography"><p>Thanks so much, your explanation helped me understand this problem 2 months later! :) It's so mind-boggling to understand how one can come up with this construction in time during the contest.</p><p>The reason I want to post here is to add something to your solution in case anyone after me has the same question. (also to just solidify my own understanding) I actually had this question myself while reading — we know that the XOR from the root to all the different leaves must be zero. But how can one prove that the XOR from one leaf to another is also zero? (a path that does not include the root, but rather just two leaves in the tree?) After all we need to make EVERY path between leaves XOR to 0</p><p>The logic is quite simple. As we said before we know XOR of the paths from the root to the two leafs, call them L1 and L2, are both zero. These paths must share some similar segment (specifically its from the LCA(L1, L2) to the root). Call the XOR of this shared segment X. Then we know the XOR from the path from L1 to LCA(L1, L2) = X, and same with the path from L2 to LCA(L1, L2). Because if (x XOR y) = 0, then x = y, and the XOR of the whole path can be broken up the XOR of two segments L1 -&gt; LCA, LCA -&gt; root. (same with L2).</p><p>The editorial also explains this logic a bit but I hope what I wrote can help. </p></div> </div> </div> <div class="reply info"> <a class="comment-650339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-650339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-650339"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602484" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602484" href="?#comment-602484" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602484" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602484" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602484"> <div class="moveup"> <div class="ttypography"><p>I cant understand the editorial of Powered Addition clearly.Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-602484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602484"> <li> <div class="comment"> <table class="comment-table" commentId="602493" commentParentId="602484"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602493" href="?#comment-602493" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602493" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602493"> <div class="moveup"> <div class="ttypography"><p>I just post my 2 cents above, hope it is easier to understand</p></div> </div> </div> <div class="reply info"> <a class="comment-602493 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602493 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602493"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602629" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ZeroNik" style="position: relative;"> <img src='https://userpic.codeforces.org/1336702/avatar/4935627333ab6d15.jpg'/> </a> <div><a href="/profile/ZeroNik" title="Pupil ZeroNik" class="rated-user user-green">ZeroNik</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602629" href="?#comment-602629" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602629" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1336702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602629"> <div class="moveup"> <div class="ttypography"><p>Who can explain problem A again. I don't undersatand why answer is n</p></div> </div> </div> <div class="reply info"> <a class="comment-602629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602629"> <li> <div class="comment"> <table class="comment-table" commentId="602636" commentParentId="602629"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/invincibel31" style="position: relative;"> <img src='https://userpic.codeforces.org/842069/avatar/78296878ae951a3.jpg'/> </a> <div><a href="/profile/invincibel31" title="Expert invincibel31" class="rated-user user-blue">invincibel31</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602636" href="?#comment-602636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602629" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="842069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602636"> <div class="moveup"> <div class="ttypography"><p>ans is equal to n bcz of the vertically standing diamonds in each way there will be only one diamond which would be standing vertically and since the number of diamond in n hence and in n</p></div> </div> </div> <div class="reply info"> <a class="comment-602636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602636"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602791" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hasnaine_" style="position: relative;"> <img src='https://userpic.codeforces.org/553185/avatar/dbae027ec9304551.jpg'/> </a> <div><a href="/profile/Hasnaine_" title="Expert Hasnaine_" class="rated-user user-blue">Hasnaine_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602791" href="?#comment-602791" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602791" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="553185" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602791"> <div class="moveup"> <div class="ttypography"><p><strong>Problem Div1(C), Div2(E):</strong> </p><p>Can anyone please elaborate on why this combination on bitmasking works?</p><p>Or, how to prove this combination works?</p><p>Thanks in advance. </p></div> </div> </div> <div class="reply info"> <a class="comment-602791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602791"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RedSnowstorm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RedSnowstorm" title="Expert RedSnowstorm" class="rated-user user-blue">RedSnowstorm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602796" href="?#comment-602796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602796" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="789793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602796"> <div class="moveup"> <div class="ttypography"><p>Could someone please elaborate a bit more on Div1 C ? I understand the solution up to the first picture, but I don't understand neither the meaning of the second picture nor the rest of the solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602796"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602873" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ateev_mishra7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ateev_mishra7" title="Pupil ateev_mishra7" class="rated-user user-green">ateev_mishra7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602873" href="?#comment-602873" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602873" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174913" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602873"> <div class="moveup"> <div class="ttypography"><p>Why does my solution to Div2-C is not working . <a href="https://codeforces.com/contest/1339/submission/76407068">https://codeforces.com/contest/1339/submission/76407068</a></p><p>can somebody please help me out on this .</p></div> </div> </div> <div class="reply info"> <a class="comment-602873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602873"> <li> <div class="comment"> <table class="comment-table" commentId="603718" commentParentId="602873"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603718" href="?#comment-603718" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603718" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603718" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603718"> <div class="moveup"> <div class="ttypography"><p>Well let's take the sequence as 1 4 1 4, your code outputs 3 while it is supposed to output 2 since you can add 1 and 2 to the third element and get a sorted output.</p></div> </div> </div> <div class="reply info"> <a class="comment-603718 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603718 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603718"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="603291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vyush" style="position: relative;"> <img src='https://userpic.codeforces.org/814106/avatar/d2c40519525d0732.jpg'/> </a> <div><a href="/profile/Vyush" title="Expert Vyush" class="rated-user user-blue">Vyush</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603291" href="?#comment-603291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603291" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603291" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603291"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain division1C/division2E I am not able to understand the approach in the editorial.I got the nim product observation but I don't know how to implement it also i don't get the editorials approach.If anyone could help that would be great.Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-603291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604316" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sheaf" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sheaf" title="Expert sheaf" class="rated-user user-blue">sheaf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 19:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604316" href="?#comment-604316" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604316" 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="604316" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="509827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604316"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, as for Div1E, isn't $$$R=in(P)\cap Q$$$, instead it is $$$R=in(V)\cap Q$$$? The latter just doesn't make sense if you consider the lemma 3. $$$in(V)$$$ is the subset of all vertices that have at least one outgoing edge, $$$in(P)\cap Q$$$ is the subset of all vertices of $$$Q$$$ that have at least one outgoing edge. Then lemma 3, which says there are edges from set $$$S$$$ to $$$R$$$, can't be true because it says that $$$S$$$ — a subset of $$$Q$$$ without outgoing edges — has edges pointing to $$$R$$$. On contrary, if we set $$$R=in(P)\cap Q$$$ we, can prove lemma 3 by forbidding the configuration from the statement. Also, can't really prove part of lemma 4 that says that $$$R$$$ has no cycles without it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604316 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604316 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604316"> <li> <div class="comment"> <table class="comment-table" commentId="604403" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604403" href="?#comment-604403" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604403" 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="604403" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604403"> <div class="moveup"> <div class="ttypography"><p>(erased)</p></div> </div> </div> <div class="reply info"> <a class="comment-604403 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604403 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604403"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604580" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 01:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604580" href="?#comment-604580" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604580" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604580" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604580"> <div class="moveup"> <div class="ttypography"><p>oops, sorry, I understood your comment wrong. To be honest, I don't fully understand approach of this problem, so I would like to call author of this problem directly. <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></p></div> </div> </div> <div class="reply info"> <a class="comment-604580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604580"> <li> <div class="comment"> <table class="comment-table" commentId="604593" commentParentId="604580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604593" href="?#comment-604593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604593" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604593"> <div class="moveup"> <div class="ttypography"><p>Ugh, bad boy. You should be more responsible to your round.</p></div> </div> </div> <div class="reply info"> <a class="comment-604593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604593"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604591" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604591" href="?#comment-604591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604591" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604591"> <div class="moveup"> <div class="ttypography"><p>Oh, I didn't realise that I used the variable $$$V$$$ 2 times. Now I fixed it. When I said $$$in(V) \cap Q$$$ I refered to the $$$V$$$ in Lemma 2. Thanks for pointinh out my mistake.</p></div> </div> </div> <div class="reply info"> <a class="comment-604591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604591"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604631" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 07:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604631" href="?#comment-604631" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604631"> <div class="moveup"> <div class="ttypography"><p>Hi, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, how does observation 1 of edge weight problem work since the shape of tree is determined by input rather than can be arbitrary constructed as in observation 1? Take example input 3 for instance. Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-604631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604631"> <li> <div class="comment"> <table class="comment-table" commentId="604757" commentParentId="604631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604757" href="?#comment-604757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604757" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604757"> <div class="moveup"> <div class="ttypography"><p><img alt="ex1" src="/predownloaded/a2/a8/a2a877e5c47802fc77cb6bee8965a15f80b6e799.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You can see that we can make $$$f = 1$$$ in this tree anyway.</p></div> </div> </div> <div class="reply info"> <a class="comment-604757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604757"> <li> <div class="comment"> <table class="comment-table" commentId="605625" commentParentId="604757"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605625" href="?#comment-605625" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604757" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605625" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605625"> <div class="moveup"> <div class="ttypography"><p>I must misunderstand your meaning, but doesn't f=2 in the graph since there are weight of 1 and 2?</p><p>Or do you mean that the edge on 7-4-3 could be equivalent to a single edge with weight of 3=weight(7,4) xor weight(4,3)=2 xor 1? Thus in this way the observation 1 can be applied?</p></div> </div> </div> <div class="reply info"> <a class="comment-605625 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605625 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605625"> <li> <div class="comment"> <table class="comment-table" commentId="605631" commentParentId="605625"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605631" href="?#comment-605631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605625" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605631"> <div class="moveup"> <div class="ttypography"><p>This picture shows how you can manage $$$f \le 3$$$ in this tree with first observation. By &quot; <em>You can see that we can make $$$f = 1$$$ in this tree any</em> &quot; I mean you can replace all weights $$$2$$$ to $$$1$$$ to make $$$f = 1$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-605631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605631"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/karanbhatia116" style="position: relative;"> <img src='https://userpic.codeforces.org/872128/avatar/afb324a25af3a491.jpg'/> </a> <div><a href="/profile/karanbhatia116" title="Newbie karanbhatia116" class="rated-user user-gray">karanbhatia116</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604739" href="?#comment-604739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872128" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604739"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain me the second test case for Div1A/Div2C(<a href="/contest/1338/problem/A" title="Codeforces Round 633 (Div. 1)">1338A - Powered Addition</a>)?</p> <pre><code>Input: 6 3 1000000000 0 -1000000000 1 6 2 -1000000000 1000000000 2 1000000000 -1000000000 2 1000000000 1000000000 2 -1000000000 -1000000000 Output: 31 0 0 31 0 0 </code></pre><p>How is the output 31 and not 32? If it is 31 then we must have added 2^30 in 0 and -1000000000 but that does not make the array non-decreasing in the first test case.</p></div> </div> </div> <div class="reply info"> <a class="comment-604739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604739"> <li> <div class="comment"> <table class="comment-table" commentId="604760" commentParentId="604739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 12:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604760" href="?#comment-604760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604760" 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="604760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604760"> <div class="moveup"> <div class="ttypography"><p>Select $$$2$$$-nd index at last second only, and $$$3$$$-rd index all the time. Then you get </p><p>$$$a = [10^{9}, 0, -10^{9}] \to [10^{9}, 0 + 2^{30}, -10^{9} + 2^{0} + 2^{1} + \ldots + 2^{30}] = [1000000000, 1073741824, 1147483647]$$$</p><p>So you can make $$$a$$$ non-decreasing in $$$31$$$ seconds.</p></div> </div> </div> <div class="reply info"> <a class="comment-604760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604760"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605553" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 09:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605553" href="?#comment-605553" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605553" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605553"> <div class="moveup"> <div class="ttypography"><p>why does the answer for div2-C depends only on largest difference? Can someone explain in detailed manner i am unable to get the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-605553 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605553 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605553"> <li> <div class="comment"> <table class="comment-table" commentId="605637" commentParentId="605553"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605637" href="?#comment-605637" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605553" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605637" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605637" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605637"> <div class="moveup"> <div class="ttypography"><p>Fact 1: $$$2^{0} + 2^{1} + \ldots + 2^{t-1} \lt 2^{t}$$$.</p><p>This means if you want to add something equal or bigger than $$$2^{t}$$$ on some position, then you should use more than $$$t$$$ seconds.</p><p>Fact 2: Required seconds is determined by maximum bit of difference.</p><p>From two facts you can observe that smaller difference leads to shorter time.</p><p>I will write few examples below;</p> <ul> <li>diff = 0 -&gt; 0 second</li> <li>diff = 1 -&gt; 1 second ($$$1 = 2^{0}$$$)</li> <li>diff = 2 -&gt; 2 seconds ($$$2 = 2^{1}$$$)</li> <li>diff = 3 -&gt; 2 seconds ($$$3 = 2^{0} + 2^{1}$$$)</li> <li>diff = 4 -&gt; 3 seconds ($$$4 = 2^{2}$$$)</li> <li>diff = 5 -&gt; 3 seconds ($$$5 = 2^{0} + 2^{2}$$$)</li> <li>diff = 6 -&gt; 3 seconds ($$$6 = 2^{1} + 2^{2}$$$)</li> <li>diff = 7 -&gt; 3 seconds ($$$7 = 2^{0} + 2^{1} + 2^{2}$$$)</li> <li>...</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-605637 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605637 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605637"> <li> <div class="comment"> <table class="comment-table" commentId="605676" commentParentId="605637"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 12:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605676" href="?#comment-605676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605637" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605676"> <div class="moveup"> <div class="ttypography"><p>Thank you for your explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-605676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605676"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605607" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anshul23" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anshul23" title="Expert anshul23" class="rated-user user-blue">anshul23</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 10:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605607" href="?#comment-605607" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605607" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="551535" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-605607"> <div class="moveup"> <div class="ttypography"><p>Nice editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-605607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605607"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grapo_Oranges" style="position: relative;"> <img src='https://userpic.codeforces.org/1443313/avatar/3242fe30f43d5e9f.jpg'/> </a> <div><a href="/profile/grapo_Oranges" title="Expert grapo_Oranges" class="rated-user user-blue">grapo_Oranges</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 13:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605691" href="?#comment-605691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605691" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605691"> <div class="moveup"> <div class="ttypography"><p>@Anyone who solved Div2. D during the contest, can you explain how did you actually figure out the solution and was there any specific problem you ever did in past that helped you to solve this problem?</p></div> </div> </div> <div class="reply info"> <a class="comment-605691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606212" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ankit_12" style="position: relative;"> <img src='https://userpic.codeforces.org/1461518/avatar/2c0c3df83d1920d2.jpg'/> </a> <div><a href="/profile/Ankit_12" title="Pupil Ankit_12" class="rated-user user-green">Ankit_12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 10:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606212" href="?#comment-606212" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="606212" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="606212" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1461518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606212"> <div class="moveup"> <div class="ttypography"><p>Why this sequence is not correct for n=9, A/C to question Perfect Triples please Any one Help???</p><p>9 : 1 2 3 4 3 7 8 4 12</p></div> </div> </div> <div class="reply info"> <a class="comment-606212 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606212 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606212"> <li> <div class="comment"> <table class="comment-table" commentId="606260" commentParentId="606212"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 13:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606260" href="?#comment-606260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606212" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606260"> <div class="moveup"> <div class="ttypography"><p>Because $$$3$$$ is used twice in your sequence.</p></div> </div> </div> <div class="reply info"> <a class="comment-606260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606260"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606777" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/striver_79" style="position: relative;"> <img src='https://userpic.codeforces.org/584222/avatar/92d0d608686eabcc.jpg'/> </a> <div><a href="/profile/striver_79" title="Candidate Master striver_79" class="rated-user user-violet">striver_79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 13:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606777" href="?#comment-606777" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606777" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="584222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606777"> <div class="moveup"> <div class="ttypography"><p>Video editorial for <a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div2D</a>/<a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div1B</a>: </p></div> </div> </div> <div class="reply info"> <a class="comment-606777 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606777 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606777"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607351" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/richikchanda1999" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/richikchanda1999" title="Pupil richikchanda1999" class="rated-user user-green">richikchanda1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 18:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607351" href="?#comment-607351" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607351" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="510979" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607351"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces,</p><p>Can anyone help me to come up with a better approach to the excluded problem (<a href="https://codeforces.com/gym/276159/problem/D1A_old">https://codeforces.com/gym/276159/problem/D1A_old</a>) apart from the brute-force approach which is giving TLE?</p></div> </div> </div> <div class="reply info"> <a class="comment-607351 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607351 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607351"> <li> <div class="comment"> <table class="comment-table" commentId="608851" commentParentId="607351"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/22/2020 18:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-608851" href="?#comment-608851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607351" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="608851" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="608851" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-608851"> <div class="moveup"> <div class="ttypography"><p>$$$x \oplus (x \cdot 2^{30}) = x \cdot (1 + 2^{30})$$$ if $$$x &lt; 2^{30}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-608851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-608851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-608851"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="619618" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/10/2020 21:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-619618" href="?#comment-619618" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="619618" 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="619618" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-619618"> <div class="moveup"> <div class="ttypography"><p>After a few weeks when I want to solve the problems I just realized the Editorial is so beautiful, those well-illustrated pictures and interesting stories made the Editorial so great!</p><p>But I had problems solving D1E. I cannot figure out why the <strong>Lemma 3</strong> and <strong>Lemma 6a/b</strong> are correct (And of course the final observations). Can you give proofs for them?</p><p><strong>UPD: After asking others, now I understood. Anyway, thanks the great Editorial!</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-619618 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-619618 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-619618"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="620074" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/11/2020 17:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620074" href="?#comment-620074" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="620074" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620074"> <div class="moveup"> <div class="ttypography"><p>i found a crazy solution of div1B <a href="https://codeforces.com/contest/1338/submission/76346806">https://codeforces.com/contest/1338/submission/76346806</a> can anyone plz explain the logic</p></div> </div> </div> <div class="reply info"> <a class="comment-620074 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620074 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620074"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="630800" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shpvb" style="position: relative;"> <img src='https://userpic.codeforces.org/720608/avatar/3fa49fe2fc134d7b.jpg'/> </a> <div><a href="/profile/shpvb" title="Candidate Master shpvb" class="rated-user user-violet">shpvb</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/27/2020 13:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-630800" href="?#comment-630800" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="630800" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-630800"> <div class="moveup"> <div class="ttypography"><p>Can someone provide insight into the mathematical induction referred to in observation 2 of div1C (Perfect Triples)?</p></div> </div> </div> <div class="reply info"> <a class="comment-630800 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-630800 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-630800"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="792521" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Livu_sz" style="position: relative;"> <img src='https://userpic.codeforces.org/1922428/avatar/3153d345afda896c.jpg'/> </a> <div><a href="/profile/Livu_sz" title="Expert Livu_sz" class="rated-user user-blue">Livu_sz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/19/2021 06:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-792521" href="?#comment-792521" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="792521" 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="792521" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1922428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-792521"> <div class="moveup"> <div class="ttypography"><p>B was tough</p></div> </div> </div> <div class="reply info"> <a class="comment-792521 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-792521 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-792521"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1064206" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sartq" style="position: relative;"> <img src='https://userpic.codeforces.org/3093050/avatar/ec7dcd19bb83efab.jpg'/> </a> <div><a href="/profile/sartq" title="Newbie sartq" class="rated-user user-gray">sartq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2023 06:30">5 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1064206" href="?#comment-1064206" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1064206" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="3093050" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1064206"> <div class="moveup"> <div class="ttypography"><p>In div2B can we solve the problem using a hashMap, like storing the values of differences of array and their indexes?</p></div> </div> </div> <div class="reply info"> <a class="comment-1064206 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1064206 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1064206"> </ul> </div> <br/> <div id="editBox-82006" 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 firstPreview82006 = true; var lastPreviewContent82006 = ''; 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=82006] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=82006] 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-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, 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:28:37</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:'81288c53eb1e161c',t:'MTY5NjcwNjkxNy4zNTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1338E
1338
E
ru
E. JYPнация
<div class="problem-statement"><div class="header"><div class="title">E. JYPнация</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><span class="tex-font-style-it">Благодаря успеху TWICE, JYP Entertainment заработала бесчисленные деньги и стала крупнейшей развлекательной компанией по рыночной капитализации. Поэтому начальник JYP решил создать новую нацию и назначил вас предоставить схему проектирования.</span></p><p>Новая нация состоит из $$$n$$$ городов и нескольких дорог между ними. JYP дал некоторые ограничения:</p><ul>   <li> Чтобы гарантировать эффективность, избегая хаоса, <span class="tex-font-style-bf">для любых $$$2$$$ разных городов $$$A$$$ и $$$B$$$, между ними существует ровно одна дорога, и она является однонаправленной. Нет дорог, соединяющих город с самим собой</span>.<p>  </p></li><li> Логотип конкурирующих компаний не должен появляться в плане, а именно: <span class="tex-font-style-bf">там не существует</span> $$$4$$$ <span class="tex-font-style-bf">различных городов</span> $$$A$$$, $$$B$$$, $$$C$$$, $$$D$$$ <span class="tex-font-style-bf">таких, что выполняется следующая конфигурация.</span> </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/71de29128b9f668c25d8435d4348a186584b2b34.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>JYP дал критерии для вашей диаграммы. Для двух городов $$$A$$$, $$$B$$$, через $$$dis(A,B)$$$ обозначим наименьшее число дорог, которое вам нужно пройти, чтобы пройти от $$$A$$$ до $$$B$$$. Если невозможно пройти от $$$A$$$ к $$$B$$$, $$$dis(A,B) = 614n$$$. Затем значение эффективности определяется как сумма $$$dis(A,B)$$$ по всем упорядоченным парам различных городов $$$(A,B)$$$.</p><p><span class="tex-font-style-bf">Обратите внимание, что $$$dis(A,B)$$$ не обязательно должно быть равно $$$dis(B,A)$$$</span>.</p><p>Вы нарисовали схему проекта, которая удовлетворяет ограничениям JYP. Найдите сумму $$$dis(A,B)$$$ по всем упорядоченным парам городов $$$(A,B)$$$ с $$$A\neq B$$$.</p><p><span class="tex-font-style-bf">Обратите внимание, что ввод дается в сжатом виде. Но даже хотя он сжат, лучше используйте быстрое считывание.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$4 \le n \le 8000$$$, $$$n \equiv 0 \pmod{4}$$$)  — количество городов.</p><p>Далее следует описание матрицы. В каждой из $$$n$$$ следующих строк следуют по $$$\frac{n}{4}$$$ однозначных чисел шестнадцатеричной системы счисления (то есть, эти числа могут задаваться либо как цифры от $$$0$$$ до $$$9$$$, либо как прописные латинские буквы от $$$A$$$ до $$$F$$$). Двоичная запись каждого из этих чисел задаёт очередные $$$4$$$ элемента матрицы в текущей строке. Например, если число равно $$$B$$$, то очередные четыре элемента матрицы равны $$$1011$$$, а если число равно $$$5$$$, то очередные четыре элемента матрицы равны $$$0101$$$.</p><p>После того, как вы получите расшифрованную двоичную матрицу, $$$j$$$-й символ $$$i$$$-й строки будет равен $$$1$$$, если односторонняя дорога между городами $$$i$$$ и $$$j$$$ направлена от $$$i$$$ к $$$j$$$, и $$$0$$$ в противном случае. Гарантируется, что граф удовлетворяет ограничениям, указанным выше.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, равное сумме $$$dis(A,B)$$$ по всем упорядоченным парам городов $$$(A,B)$$$ с $$$A\neq B$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 7 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7380 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 7F 3F 1F 0C 06 03 11 18 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 88464 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый пример соответствует матрице:</p><p>$$$\begin{matrix} 0111 \\ 0010 \\ 0001 \\ 0100 \\ \end{matrix}$$$</p><p>Которая соответствует следующему графу:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/464ea5f1e69cf670271c368e51106b6e813ae987.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>$$$dis(1,2)=dis(1,3)=dis(1,4)=dis(2,3)=dis(3,4)=dis(4,2)=1$$$</p><p>$$$dis(2,4)=dis(4,3)=dis(3,2)=2$$$</p><p>$$$dis(2,1)=dis(3,1)=dis(4,1)=2456$$$</p><p>Поэтому ответ на диаграмму составляет $$$7380$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="0034b11614ff4e77da36b1476102f4d1"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="5c85cbb657e064c2cfa3c38de5074b5925e3ec82"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='0034b11614ff4e77da36b1476102f4d1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1338%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='0034b11614ff4e77da36b1476102f4d1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1338">Codeforces Round 633 (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='0034b11614ff4e77da36b1476102f4d1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1338/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound 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='0034b11614ff4e77da36b1476102f4d1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590535"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0034b11614ff4e77da36b1476102f4d1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590535"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10753" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10760" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1338">Задачи</a></li> <li><a href="/contest/1338/submit">Отослать</a></li> <li><a href="/contest/1338/my">Мои посылки</a></li> <li><a href="/contest/1338/status">Статус</a></li> <li><a href="/contest/1338/hacks">Взломы</a></li> <li><a href="/contest/1338/room/1">Комната</a></li> <li><a href="/contest/1338/standings">Положение</a></li> <li><a href="/contest/1338/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b17476bb8ab5b1216fedc0282cf2761b3b29e712"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. JYPнация</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><span class="tex-font-style-it">Благодаря успеху TWICE, JYP Entertainment заработала бесчисленные деньги и стала крупнейшей развлекательной компанией по рыночной капитализации. Поэтому начальник JYP решил создать новую нацию и назначил вас предоставить схему проектирования.</span></p><p>Новая нация состоит из $$$n$$$ городов и нескольких дорог между ними. JYP дал некоторые ограничения:</p><ul>   <li> Чтобы гарантировать эффективность, избегая хаоса, <span class="tex-font-style-bf">для любых $$$2$$$ разных городов $$$A$$$ и $$$B$$$, между ними существует ровно одна дорога, и она является однонаправленной. Нет дорог, соединяющих город с самим собой</span>.<p>  </p></li><li> Логотип конкурирующих компаний не должен появляться в плане, а именно: <span class="tex-font-style-bf">там не существует</span> $$$4$$$ <span class="tex-font-style-bf">различных городов</span> $$$A$$$, $$$B$$$, $$$C$$$, $$$D$$$ <span class="tex-font-style-bf">таких, что выполняется следующая конфигурация.</span> </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/71de29128b9f668c25d8435d4348a186584b2b34.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>JYP дал критерии для вашей диаграммы. Для двух городов $$$A$$$, $$$B$$$, через $$$dis(A,B)$$$ обозначим наименьшее число дорог, которое вам нужно пройти, чтобы пройти от $$$A$$$ до $$$B$$$. Если невозможно пройти от $$$A$$$ к $$$B$$$, $$$dis(A,B) = 614n$$$. Затем значение эффективности определяется как сумма $$$dis(A,B)$$$ по всем упорядоченным парам различных городов $$$(A,B)$$$.</p><p><span class="tex-font-style-bf">Обратите внимание, что $$$dis(A,B)$$$ не обязательно должно быть равно $$$dis(B,A)$$$</span>.</p><p>Вы нарисовали схему проекта, которая удовлетворяет ограничениям JYP. Найдите сумму $$$dis(A,B)$$$ по всем упорядоченным парам городов $$$(A,B)$$$ с $$$A\neq B$$$.</p><p><span class="tex-font-style-bf">Обратите внимание, что ввод дается в сжатом виде. Но даже хотя он сжат, лучше используйте быстрое считывание.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$4 \le n \le 8000$$$, $$$n \equiv 0 \pmod{4}$$$)  — количество городов.</p><p>Далее следует описание матрицы. В каждой из $$$n$$$ следующих строк следуют по $$$\frac{n}{4}$$$ однозначных чисел шестнадцатеричной системы счисления (то есть, эти числа могут задаваться либо как цифры от $$$0$$$ до $$$9$$$, либо как прописные латинские буквы от $$$A$$$ до $$$F$$$). Двоичная запись каждого из этих чисел задаёт очередные $$$4$$$ элемента матрицы в текущей строке. Например, если число равно $$$B$$$, то очередные четыре элемента матрицы равны $$$1011$$$, а если число равно $$$5$$$, то очередные четыре элемента матрицы равны $$$0101$$$.</p><p>После того, как вы получите расшифрованную двоичную матрицу, $$$j$$$-й символ $$$i$$$-й строки будет равен $$$1$$$, если односторонняя дорога между городами $$$i$$$ и $$$j$$$ направлена от $$$i$$$ к $$$j$$$, и $$$0$$$ в противном случае. Гарантируется, что граф удовлетворяет ограничениям, указанным выше.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, равное сумме $$$dis(A,B)$$$ по всем упорядоченным парам городов $$$(A,B)$$$ с $$$A\neq B$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 7 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7380 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 7F 3F 1F 0C 06 03 11 18 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 88464 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый пример соответствует матрице:</p><p>$$$\begin{matrix} 0111 \\ 0010 \\ 0001 \\ 0100 \\ \end{matrix}$$$</p><p>Которая соответствует следующему графу:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/464ea5f1e69cf670271c368e51106b6e813ae987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>$$$dis(1,2)=dis(1,3)=dis(1,4)=dis(2,3)=dis(3,4)=dis(4,2)=1$$$</p><p>$$$dis(2,4)=dis(4,3)=dis(3,2)=2$$$</p><p>$$$dis(2,1)=dis(3,1)=dis(4,1)=2456$$$</p><p>Поэтому ответ на диаграмму составляет $$$7380$$$.</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/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:39</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e0e8e377a6d',t:'MTY5NjY2NTY5OS43MTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*3500"]
https://codeforces.com/blog/entry/75913
<!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="8bc765f3680682fd8f2decef62cad97d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Codeforces Round #633 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #633 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='8bc765f3680682fd8f2decef62cad97d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F75913">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='8bc765f3680682fd8f2decef62cad97d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:36:25</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:36:25</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='8bc765f3680682fd8f2decef62cad97d'/> <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/McDic">McDic</a></li> <li class="current selectedLava"><a href="/blog/McDic">Blog</a></li> <li><a href="/teams/with/McDic">Teams</a></li> <li><a href="/submissions/McDic">Submissions</a></li> <li><a href="/groups/with/McDic">Groups</a></li> <li><a href="/contests/with/McDic">Contests</a></li> <li><a href="/contests/writer/McDic">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/McDic" style="text-decoration:none;color:black !important;">McDic's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="76444"> <div class="title"> <a href="/blog/entry/75913"> <p>Codeforces Round #633 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a>, <a href="/topic/76444/en2">history</a>, <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p>Hello! I hope all of you enjoyed my contest!</p> <div class="problemTutorial" problemcode="1339A">Tutorial is loading...</div><p><strong>Behind story of A</strong>:</p> <ul> <li>I tried to make the easiest Div2A ever. Will it work? :)</li> </ul> <div class="problemTutorial" problemcode="1339B">Tutorial is loading...</div><p><strong>Behind story of B</strong>:</p> <ul> <li>I tried to block various heuristics. There were some critical heuristics which could pass so many cases. Fortunately I blocked them during testing period, so I hope there won't be much FST this time.</li> </ul> <div class="problemTutorial" problemcode="1338A">Tutorial is loading...</div><p><strong>Behind story of D2C/D1A</strong>:</p> <ul> <li>Originally, there was a different problem for this position. But it used XOR. As I made new D2E/D1C problem, I threw old D2C/D1A away and put this.</li> </ul> <div class="problemTutorial" problemcode="1338B">Tutorial is loading...</div><p><strong>Behind story of D2D/D1B</strong>:</p> <ul> <li>This problem is the most popular problem among testers. I also like this problem a lot.</li> </ul> <div class="problemTutorial" problemcode="1338C">Tutorial is loading...</div><p><strong>Behind story of D2E/D1C</strong>:</p> <ul> <li>Feedback for this problem was too different by testers.</li> <li>I made this problem by modifying <a href="https://codeforces.com/contest/1242/problem/D">Number Discovery</a>, which is one of my previous problems.</li> <li>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this.</li> </ul> <div class="problemTutorial" problemcode="1338D">Tutorial is loading...</div><p><strong>Behind story of D1D</strong>:</p> <ul> <li>This problem was supposed to be D2E at first. But all LGM testers failed this problem during VC, so we thought that this problem's difficulty is high. Meanwhile, I found that old D1D problem can be easily googled, so we removed that problem, push this problem to be D1D, and made another D1C problem. I will share old D1D later.</li> </ul> <div class="problemTutorial" problemcode="1338E">Tutorial is loading...</div><p><strong>Behind story of D1E</strong>:</p> <ul> <li>Thanks <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a> for writing this problem. She is genius in both singing and problemsolving.</li> </ul></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/1338" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 1)</a> </span> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1339" class="notice" style="text-decoration: none;">Codeforces Round 633 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-88959-76444").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "88959", blogEntryId: "75913", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=mcdic" class="tag notice" style="text-decoration: none;">mcdic</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-76444"><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'>+346</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-76444"><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/McDic"><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/McDic"> McDic </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/12/2020 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/75913#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/75913#comments"> 225 </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="82006"> <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 (171)</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="601867" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stefdasca" style="position: relative;"> <img src='https://userpic.codeforces.org/492453/avatar/429fc64e07ff3f4.jpg'/> </a> <div><a href="/profile/stefdasca" title="Candidate Master stefdasca" class="rated-user user-violet">stefdasca</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601867" href="?#comment-601867" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601867" 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="601867" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="492453" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601867"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=crOSe84Q6HQ">Video tutorial for div1A/div2C</a></p><p><a href="https://www.youtube.com/watch?v=MMtnJDMM3IE">Video tutorial for div1B/div2D</a></p></div> </div> </div> <div class="reply info"> <a class="comment-601867 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601867 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601867"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601870" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kerO_o" style="position: relative;"> <img src='https://userpic.codeforces.org/406813/avatar/a505f416e75a37bd.jpg'/> </a> <div><a href="/profile/kerO_o" title="Master kerO_o" class="rated-user user-orange">kerO_o</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601870" href="?#comment-601870" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601870" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="406813" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601870"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-601870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601870"> <li> <div class="comment"> <table class="comment-table" commentId="601963" commentParentId="601870"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601963" href="?#comment-601963" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601963" class="CommentVoteFrame" data-commentRating="30" 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:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601963"> <div class="moveup"> <div class="ttypography"><p>what does this &quot;orz&quot; mean? </p></div> </div> </div> <div class="reply info"> <a class="comment-601963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601963"> <li> <div class="comment"> <table class="comment-table" commentId="602114" commentParentId="601963"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yash18" style="position: relative;"> <img src='https://userpic.codeforces.org/858176/avatar/3cdce86e6de339b8.jpg'/> </a> <div><a href="/profile/yash18" title="Pupil yash18" class="rated-user user-green">yash18</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602114" href="?#comment-602114" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602114" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602114" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="858176" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602114"> <div class="moveup"> <div class="ttypography"><p>Bow down! Bow down to the <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602114 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602114 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602114"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601879" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SkySurfer" style="position: relative;"> <img src='https://userpic.codeforces.org/684272/avatar/41e617735365cc0e.jpg'/> </a> <div><a href="/profile/SkySurfer" title="Specialist SkySurfer" class="rated-user user-cyan">SkySurfer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601879" href="?#comment-601879" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601879" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="684272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601879"> <div class="moveup"> <div class="ttypography"><p>Best Editorial Ever ....Nice Explanation Of both Problems and Solutions . </p></div> </div> </div> <div class="reply info"> <a class="comment-601879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601879"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601890" href="?#comment-601890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601890" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601890" class="CommentVoteFrame" data-commentRating="32" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+32</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601890"> <div class="moveup"> <div class="ttypography"><p>For Div1C, I found out that the nth tuple (an, bn, cn) is basically this: (found via OEIS)</p> <ol> <li><p>an -&gt; nth number with odd number of bits</p></li> <li><p>bn -&gt; nim_multiplcation(2, an) (<a href="https://oeis.org/A006015">https://oeis.org/A006015</a>)</p></li> <li><p>cn = an ^ bn.</p></li> </ol><p>But I was still not able to solve the problem because I didn't know nim multiplication nor did I find any implementation over the net.</p></div> </div> </div> <div class="reply info"> <a class="comment-601890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601890"> <li> <div class="comment"> <table class="comment-table" commentId="601914" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601914" href="?#comment-601914" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601914" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601914"> <div class="moveup"> <div class="ttypography"><p>Nim Arithmetic is definitely overkill for this problem. </p></div> </div> </div> <div class="reply info"> <a class="comment-601914 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601914 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601914"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="601919" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601919" href="?#comment-601919" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601919" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601919" class="CommentVoteFrame" data-commentRating="71" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+71</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601919"> <div class="moveup"> <div class="ttypography"><p>We found that during testing and thought it wasn't much of an issue exactly because of that, probably you'd spend more time searching about nim multiplication than if you just solved the problem lol</p></div> </div> </div> <div class="reply info"> <a class="comment-601919 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601919 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601919"> <li> <div class="comment"> <table class="comment-table" commentId="601942" commentParentId="601919"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aviroop123" style="position: relative;"> <img src='https://userpic.codeforces.org/494338/avatar/9ae5461a2f94a27f.jpg'/> </a> <div><a href="/profile/aviroop123" title="Master aviroop123" class="rated-user user-orange">aviroop123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601942" href="?#comment-601942" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601919" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601942" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="494338" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601942"> <div class="moveup"> <div class="ttypography"><p>Yeah, that is what happened ... I kept on searching for nim multiplcation here and there and wasted too much time. I should have come up with some other approaches ... </p></div> </div> </div> <div class="reply info"> <a class="comment-601942 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601942 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601942"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602731" commentParentId="601890"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602731" href="?#comment-602731" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601890" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602731" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602731"> <div class="moveup"> <div class="ttypography"><p>A solution with nim multiplcation: <a href="/contest/1338/submission/76499145" title="Submission 76499145 by amane-ame">76499145</a></p><p>There is no doubt that it is much more complicated than the general solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602731 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602731 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602731"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601893" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Endagorion" style="position: relative;"> <img src='https://userpic.codeforces.org/1643/avatar/5c0b493cf8428ab6.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Endagorion" title="International Grandmaster Endagorion" class="rated-user user-red">Endagorion</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601893" href="?#comment-601893" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601893" class="CommentVoteFrame" data-commentRating="192" data-commentUserId="1643" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+192</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601893"> <div class="moveup"> <div class="ttypography"><p>I don't have proof, but in div1C any triple appears to be $$$(x, x \otimes 2, x \otimes 3)$$$, where $$$\otimes$$$ is nim multiplication.</p></div> </div> </div> <div class="reply info"> <a class="comment-601893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601893"> <li> <div class="comment"> <table class="comment-table" commentId="601983" commentParentId="601893"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601983" href="?#comment-601983" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601983" class="CommentVoteFrame" data-commentRating="64" 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;">+64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601983"> <div class="moveup"> <div class="ttypography"><p>:o</p></div> </div> </div> <div class="reply info"> <a class="comment-601983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601983"> <li> <div class="comment"> <table class="comment-table" commentId="602418" commentParentId="601983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jerry__Jiang" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jerry__Jiang" title="Master Jerry__Jiang" class="rated-user user-orange">Jerry__Jiang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602418" href="?#comment-602418" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601983" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602418" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1198521" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602418"> <div class="moveup"> <div class="ttypography"><p>:)</p></div> </div> </div> <div class="reply info"> <a class="comment-602418 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602418 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602418"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601939" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601939" href="?#comment-601939" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601939" 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="601939" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-41" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601939"> <div class="moveup"> <div class="ttypography"><p>[DELETED]</p></div> </div> </div> <div class="reply info"> <a class="comment-601939 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601939 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601939"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prodelta" style="position: relative;"> <img src='https://userpic.codeforces.org/847522/avatar/e144f36263828062.jpg'/> </a> <div><a href="/profile/prodelta" title="Pupil prodelta" class="rated-user user-green">prodelta</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601950" href="?#comment-601950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601950" class="CommentVoteFrame" data-commentRating="62" data-commentUserId="847522" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601950"> <div class="moveup"> <div class="ttypography"><p>System testing is finished , Editorials are out , but my submission for Problem — A still shows Pretests Passed . Link : <a href="https://codeforces.com/contest/1339/submission/76340409">Here</a></p><p>Have I committed some fatal sin for which I am being given such a brutal punishment ?</p><p>What should I do now ?</p></div> </div> </div> <div class="reply info"> <a class="comment-601950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601950"> <li> <div class="comment"> <table class="comment-table" commentId="601964" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shubhammitt" style="position: relative;"> <img src='https://userpic.codeforces.org/785906/avatar/ecb76ca8bc2663f4.jpg'/> </a> <div><a href="/profile/shubhammitt" title="Expert shubhammitt" class="rated-user user-blue">shubhammitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601964" href="?#comment-601964" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601964" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="785906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601964"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-601964 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601964 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601964"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602003" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602003" href="?#comment-602003" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602003" 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-602003"> <div class="moveup"> <div class="ttypography"><p>xd</p></div> </div> </div> <div class="reply info"> <a class="comment-602003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602003"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602451" commentParentId="601950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chidoring" style="position: relative;"> <img src='https://userpic.codeforces.org/1455809/avatar/d62042cde12a7b4e.jpg'/> </a> <div><a href="/profile/chidoring" title="Pupil chidoring" class="rated-user user-green">chidoring</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602451" href="?#comment-602451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602451" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1455809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602451"> <div class="moveup"> <div class="ttypography"><p>rip</p></div> </div> </div> <div class="reply info"> <a class="comment-602451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602451"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601953" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_DynamicCube" style="position: relative;"> <img src='https://userpic.codeforces.org/1381092/avatar/ca9726e93700302b.jpg'/> </a> <div><a href="/profile/_DynamicCube" title="Pupil _DynamicCube" class="rated-user user-green">_DynamicCube</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601953" href="?#comment-601953" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601953" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1381092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601953"> <div class="moveup"> <div class="ttypography"><p>재밌는 문제들 감사합니다! (Thank you for the interesting questions!)</p></div> </div> </div> <div class="reply info"> <a class="comment-601953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601953"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601956" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AceKing" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AceKing" title="Candidate Master AceKing" class="rated-user user-violet">AceKing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601956" href="?#comment-601956" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601956" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="910788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601956"> <div class="moveup"> <div class="ttypography"><p>Fastest editorial I have ever seen!</p></div> </div> </div> <div class="reply info"> <a class="comment-601956 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601956 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601956"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601960" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601960" href="?#comment-601960" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601960" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601960" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-601960"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces, I don't have any idea how to approach problems like Div2.D/Div1.B, can someone give me an advice? I am not sure what should I learn first in order to be able to come with a solution to this problem. Thanks :)</p></div> </div> </div> <div class="reply info"> <a class="comment-601960 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601960 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601960"> <li> <div class="comment"> <table class="comment-table" commentId="602364" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 06:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602364" href="?#comment-602364" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602364" class="CommentVoteFrame" data-commentRating="3" 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: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-602364"> <div class="moveup"> <div class="ttypography"><p>From my experience, Div 2 D tends to vary quite bit. I think the best way to go about it is to just keep on practicing a bunch of div 2 D, and look at editorials if you don't quite understand. Also, nice profile picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602364"> <li> <div class="comment"> <table class="comment-table" commentId="602461" commentParentId="602364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TheRedLegend" style="position: relative;"> <img src='https://userpic.codeforces.org/456772/avatar/1c2a786251f81051.jpg'/> </a> <div><a href="/profile/TheRedLegend" title="Expert TheRedLegend" class="rated-user user-blue">TheRedLegend</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602461" href="?#comment-602461" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602364" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602461" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602461" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="456772" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602461"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, I will keep practicing then :D. PS: I also like your picture :)</p></div> </div> </div> <div class="reply info"> <a class="comment-602461 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602461 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602461"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602499" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602499" href="?#comment-602499" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602499" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602499"> <div class="moveup"> <div class="ttypography"><p>Well from my experience, it appears atleast one of C/D almost always involves graphs and/or DP. I'd recommend first learning all about graphs, especially some important techniques like DFS, BFS, multi-source BFS, SCC, bridges, cut-vertices etc.[Graphs are really awesome :] Then later move on to DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-602499 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602499 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602499"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604120" commentParentId="601960"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 16:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604120" href="?#comment-604120" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601960" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604120" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604120"> <div class="moveup"> <div class="ttypography"><p>IMO you should first learn a little advanced algorithms and data structures and etc., also solve-up contests and past ones, i say the best way is to take virtual contests and then solve the rest of the problems excluding the cases you full the contest :). Also solve Div2.E after the contests, it's fine if you cant solve them, just take your time and try your best then go to editorial and make sure you fully understand the editorial and the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604120"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601962" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601962" href="?#comment-601962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601962" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-118" 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;">-118</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601962"> <div class="moveup"> <div class="ttypography"><p>i think it is better to provide codes instead of stories</p></div> </div> </div> <div class="reply info"> <a class="comment-601962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601962"> <li> <div class="comment"> <table class="comment-table" commentId="601995" commentParentId="601962"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601995" href="?#comment-601995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601995" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601995"> <div class="moveup"> <div class="ttypography"><p>That's why the button showing number of solves next to a problem exists. Click on that and you can see many codes and sort by speed, code length, etc.</p></div> </div> </div> <div class="reply info"> <a class="comment-601995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601995"> <li> <div class="comment"> <table class="comment-table" commentId="601999" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601999" href="?#comment-601999" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601999" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-30" 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;">-30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601999"> <div class="moveup"> <div class="ttypography"><p>I know that, But I want to see the code of the explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-601999 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601999 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601999"> <li> <div class="comment"> <table class="comment-table" commentId="602002" commentParentId="601999"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602002" href="?#comment-602002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601999" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602002" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602002"> <div class="moveup"> <div class="ttypography"><p>Wtf does that mean. Every code is most likely some variation of the explanation if it passed...</p></div> </div> </div> <div class="reply info"> <a class="comment-602002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602002"> <li> <div class="comment"> <table class="comment-table" commentId="602006" commentParentId="602002"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 20:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602006" href="?#comment-602006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602002" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602006" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-55" 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;">-55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602006"> <div class="moveup"> <div class="ttypography"><p>No</p></div> </div> </div> <div class="reply info"> <a class="comment-602006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602006"> <li> <div class="comment"> <table class="comment-table" commentId="602113" commentParentId="602006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602113" href="?#comment-602113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602113" class="CommentVoteFrame" data-commentRating="20" 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: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-602113"> <div class="moveup"> <div class="ttypography"><p>Yes</p></div> </div> </div> <div class="reply info"> <a class="comment-602113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602113"> <li> <div class="comment"> <table class="comment-table" commentId="602122" commentParentId="602113"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 21:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602122" href="?#comment-602122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602113" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602122" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-38" 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;">-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-602122"> <div class="moveup"> <div class="ttypography"><p>No is no</p></div> </div> </div> <div class="reply info"> <a class="comment-602122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602122"> <li> <div class="comment"> <table class="comment-table" commentId="602331" commentParentId="602122"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602331" href="?#comment-602331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602331" class="CommentVoteFrame" data-commentRating="41" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+41</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602331"> <div class="moveup"> <div class="ttypography"><p>Dumb is dumb</p></div> </div> </div> <div class="reply info"> <a class="comment-602331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602331"> <li> <div class="comment"> <table class="comment-table" commentId="602624" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 15:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602624" href="?#comment-602624" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602624" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" 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;">-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-602624"> <div class="moveup"> <div class="ttypography"><p>Who is dumb there?</p></div> </div> </div> <div class="reply info"> <a class="comment-602624 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602624 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602624"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604121" commentParentId="602331"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeadlyCritic" style="position: relative;"> <img src='https://userpic.codeforces.org/923556/avatar/4e6507102886a4ec.jpg'/> </a> <div><a href="/profile/DeadlyCritic" title="Master DeadlyCritic" class="rated-user user-orange">DeadlyCritic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:02">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604121" href="?#comment-604121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602331" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604121" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="923556" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604121"> <div class="moveup"> <div class="ttypography"><p>BABA IS YOU</p></div> </div> </div> <div class="reply info"> <a class="comment-604121 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604121 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604121"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604142" commentParentId="604121"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/u68_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/u68_" title="Master u68_" class="rated-user user-orange">u68_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 17:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604142" href="?#comment-604142" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604142" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1328304" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604142"> <div class="moveup"> <div class="ttypography"><p>Who is BABA?</p></div> </div> </div> <div class="reply info"> <a class="comment-604142 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604142 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604142"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604648" commentParentId="604142"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Suleyman.A" style="position: relative;"> <img src='https://userpic.codeforces.org/82791/avatar/fc8479c7406b79a3.jpg'/> </a> <div><a href="/profile/Suleyman.A" title="Expert Suleyman.A" class="rated-user user-blue">Suleyman.A</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604648" href="?#comment-604648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604142" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604648" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="82791" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604648"> <div class="moveup"> <div class="ttypography"><p>He is husband of your mother</p></div> </div> </div> <div class="reply info"> <a class="comment-604648 en true" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604648 en true" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604648"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602019" commentParentId="601995"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602019" href="?#comment-602019" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-601995" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602019" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602019"> <div class="moveup"> <div class="ttypography"><p>Its always better if editorial provides code or snippet about their approach</p></div> </div> </div> <div class="reply info"> <a class="comment-602019 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602019 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602019"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601975" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rajiv_kale" style="position: relative;"> <img src='https://userpic.codeforces.org/758545/avatar/575c69bbc5b5a715.jpg'/> </a> <div><a href="/profile/rajiv_kale" title="Newbie rajiv_kale" class="rated-user user-gray">rajiv_kale</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601975" href="?#comment-601975" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="601975" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="601975" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="758545" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-601975"> <div class="moveup"> <div class="ttypography"><p>Good editorial. I especially liked those behind stories.</p></div> </div> </div> <div class="reply info"> <a class="comment-601975 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601975 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601975"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="601992" commentParentId="-1"> <tr> <td class="left"> <div style="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="Apr/12/2020 20:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-601992" href="?#comment-601992" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="601992" class="CommentVoteFrame" data-commentRating="8" 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;">+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-601992"> <div class="moveup"> <div class="ttypography"><p>My E looks very different, now I'm wondering if it's correct.</p><p>Let's focus only on one big strongly connected component. For each vertex $$$V$$$ all the vertices which point to $$$V$$$ are ordered in a path. So, maybe it's possible to somehow form a cycle from all the vertices from the SCC. Let's take any vertex $$$V$$$. Now, from all the vertices which point to the $$$V$$$ let's take the last one on this path, let's call it $$$U$$$. Fix $$$U$$$ before $$$V$$$ on this cycle. Now, in the same manner, find a vertex that will be before $$$U$$$. And so on until we have a full cycle. My guess is that it's correct and that after this process which vertex points to some interval on the cycle which starts in this vertex. With such a form of the graph, we can easily calculate the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-601992 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-601992 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-601992"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602013" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602013" href="?#comment-602013" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602013" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-62" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-602013"> <div class="moveup"> <div class="ttypography"><p>Im not gonna lie but div2 was not interesting at all, problems D and E just required some basic observation. I hope future rounds require some more algorithmic skills to solve D and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-602013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602013"> <li> <div class="comment"> <table class="comment-table" commentId="602039" commentParentId="602013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602039" href="?#comment-602039" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602039" class="CommentVoteFrame" data-commentRating="100" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+100</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602039"> <div class="moveup"> <div class="ttypography"><p>How come did you only solve A then?</p></div> </div> </div> <div class="reply info"> <a class="comment-602039 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602039 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602039"> <li> <div class="comment"> <table class="comment-table" commentId="602102" commentParentId="602039"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bored69" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bored69" title="Unrated, bored69" class="rated-user user-black">bored69</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602102" href="?#comment-602102" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602039" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602102" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-40" data-commentUserId="1476328" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602102"> <div class="moveup"> <div class="ttypography"><p>The point is not how many problems I solved or not but about the quality of problems, pls dont divert issues like this. (btw that submission to A is after contest :p)</p></div> </div> </div> <div class="reply info"> <a class="comment-602102 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602102 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602102"> <li> <div class="comment"> <table class="comment-table" commentId="602128" commentParentId="602102"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-is-this-fft-" 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/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602128" href="?#comment-602128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602102" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602128" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="273873" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602128"> <div class="moveup"> <div class="ttypography"><p>OK, I'm sorry.</p><p>Well, I thought they were good :D. It's kinda subjective. Who's to say &quot;making observations&quot; is worse than &quot;algorithmic skills&quot;? I don't think it's so much about &quot;quality of problems&quot; than &quot;style of problems&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-602128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602128"> <li> <div class="comment"> <table class="comment-table" commentId="602144" commentParentId="602128"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602144" href="?#comment-602144" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602144" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602144"> <div class="moveup"> <div class="ttypography"><p>I agree it's about style problems and I also liked the problems today. However I do agree with <a class="rated-user user-black" href="/profile/bored69" title="Unrated, bored69">bored69</a> that imo too many problems are extremely short to code while relying solely on observation. While I know many people enjoy the short to code problems, it is called _code_forces after all, so I think the solution should be longer than 10 lines to solve the problem, and I would enjoy getting to use some standard algorithms more often as long as the problem is still not straight application</p></div> </div> </div> <div class="reply info"> <a class="comment-602144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602144"> <li> <div class="comment"> <table class="comment-table" commentId="602407" commentParentId="602144"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lessmeaning" style="position: relative;"> <img src='https://userpic.codeforces.org/400632/avatar/4aeb556dedbc357a.jpg'/> </a> <div><a href="/profile/lessmeaning" title="Master lessmeaning" class="rated-user user-orange">lessmeaning</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602407" href="?#comment-602407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602144" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602407" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="400632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602407"> <div class="moveup"> <div class="ttypography"><p>Another Radewoosh's pawn</p></div> </div> </div> <div class="reply info"> <a class="comment-602407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602407"> <li> <div class="comment"> <table class="comment-table" commentId="602903" commentParentId="602407"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SuperJ6" style="position: relative;"> <img src='https://userpic.codeforces.org/764717/avatar/fd5ad834b5e07bc3.jpg'/> </a> <div><a href="/profile/SuperJ6" title="Master SuperJ6" class="rated-user user-orange">SuperJ6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602903" href="?#comment-602903" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602407" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602903" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="764717" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602903"> <div class="moveup"> <div class="ttypography"><p>Maybe Radewoosh is my pawn ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-602903 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602903 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602903"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602017" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602017" href="?#comment-602017" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602017" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602017"> <div class="moveup"> <div class="ttypography"><p>In Div 2-D explanation, I am not able to understand e-l+m part. Can someone help? </p></div> </div> </div> <div class="reply info"> <a class="comment-602017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602017"> <li> <div class="comment"> <table class="comment-table" commentId="602185" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602185" href="?#comment-602185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602185" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602185"> <div class="moveup"> <div class="ttypography"><p>The key construction in the editorial is that for every leaf i, the edge between i and its parent is xor(path(root,parent(i))). This construction guarantees different weights with one exception, what if multiple leaves have same parent? In that case we'll have only one extra distinct weight for all leaves with a common parent. So instead of including weights for all the leaves, we'll include weights only for their parents. Hence, first assume all edges as distinct and include them all(e) , then remove all leaves(l) and finally add those parents (which are non-leaf nodes with atleast one child as leaf (m)). So, we get e-l+m.</p></div> </div> </div> <div class="reply info"> <a class="comment-602185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602185"> <li> <div class="comment"> <table class="comment-table" commentId="602260" commentParentId="602185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:35">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602260" href="?#comment-602260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602185" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602260"> <div class="moveup"> <div class="ttypography"><p>I checked your solution. I am having some doubts. 1- Why did you choose your node as the vertex with a maximum degree? 2- The minimum f condition says if only odd paths are there, the minimum f is 1. forex. like 1--2--3--4(-- is an edge), how only one number can ensure bitwise XOR of 0?</p></div> </div> </div> <div class="reply info"> <a class="comment-602260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602260"> <li> <div class="comment"> <table class="comment-table" commentId="602286" commentParentId="602260"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rath772k" style="position: relative;"> <img src='https://userpic.codeforces.org/589389/avatar/ff63c7bfd1cd1e2e.jpg'/> </a> <div><a href="/profile/rath772k" title="Candidate Master rath772k" class="rated-user user-violet">rath772k</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602286" href="?#comment-602286" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602260" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602286" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="589389" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602286"> <div class="moveup"> <div class="ttypography"><ol> <li>I had a different approach when I started coding, so i start with that node with maximum degre. In my approach, the necessary condition is that root node should not be leaf, if it is I'll not count one leaf in my dfs leading to a wrong answer.</li> <li>Minimum condition for f is, all leaf nodes should be at a distance of same parity from root, so that every pair of leaves are separated by even no. Of edges.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-602286 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602286 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602286"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602209" commentParentId="602017"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602209" href="?#comment-602209" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602017" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602209" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602209"> <div class="moveup"> <div class="ttypography"><p>What about the case when edges with same weight are counted twice? In the picture Observation 3, the edges (1)-(2) and (2)-(6) should have the same weight. But the formula will count them as separate weights. Can someone please explain&gt;</p></div> </div> </div> <div class="reply info"> <a class="comment-602209 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602209 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602209"> <li> <div class="comment"> <table class="comment-table" commentId="602232" commentParentId="602209"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rachit901" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rachit901" title="Specialist rachit901" class="rated-user user-cyan">rachit901</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:52">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602232" href="?#comment-602232" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602209" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602232" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="708345" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602232"> <div class="moveup"> <div class="ttypography"><p>No, it won't be counted twice. edges 1-2 and 2-6 are first removed by subtracting l (e-l) and then added once for their common parent 2(non-leaf node with 2 leaves) through m (e-l+m)</p></div> </div> </div> <div class="reply info"> <a class="comment-602232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602232"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602029" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaaven" style="position: relative;"> <img src='https://userpic.codeforces.org/851917/avatar/442eaf7f5f3f896b.jpg'/> </a> <div><a href="/profile/vaaven" title="Master vaaven" class="rated-user user-orange">vaaven</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602029" href="?#comment-602029" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602029" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="851917" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602029"> <div class="moveup"> <div class="ttypography"><p>Thank you for interesting and hard problems, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a>!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-602029 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602029 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602029"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602042" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602042" href="?#comment-602042" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602042" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602042" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602042"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1338/problem/B" title="Codeforces Round 633 (Div. 1)">1338B - Edge Weight Assignment</a> Dont get it how the construction works at all. Should't there be some recursion as we do a dfs? How/where do we start, and what to do in &quot;each step&quot;, assuming there are steps?</p></div> </div> </div> <div class="reply info"> <a class="comment-602042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602042"> <li> <div class="comment"> <table class="comment-table" commentId="602203" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AdsT" style="position: relative;"> <img src='https://userpic.codeforces.org/639570/avatar/f12b9c2694f9e204.jpg'/> </a> <div><a href="/profile/AdsT" title="Expert AdsT" class="rated-user user-blue">AdsT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602203" href="?#comment-602203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602203" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="639570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602203"> <div class="moveup"> <div class="ttypography"><p>I agree, everyone seemed to have just done the same thing, take one from the back and one from the front, I just am not able to prove this. How do I come to this conclusion?</p></div> </div> </div> <div class="reply info"> <a class="comment-602203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602203"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602348" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602348" href="?#comment-602348" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602348" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602348"> <div class="moveup"> <div class="ttypography"><p>This is a way that I came up with to always satisfy 3 distinct colors for every tree.</p><p>Choose a leaf (called $$$u$$$) and choose the connected node with this leaf (called $$$r$$$ and obviously this node won't be a leaf, as $$$n &gt;= 3$$$) as the root.</p><p>What we are going to construct is we are trying to make: $$$ xor(path(r, v)) = xor(path(r, u)) $$$ for every leaf $$$v$$$. Because when $$$ xor(path(r, v)) = xor(path(r, u)) $$$ then $$$ xor(path(r, v_1)) = xor(path(r, v_2)) ( = xor(path(r, u)))$$$ for every pair of leaves.</p><p>We have $$$xor(path(r, v_1)) = xor(path(r, v_2)) $$$ $$$\Leftrightarrow (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_1))) = (xor(path(r, lca(v_1, v_2))) \oplus xor(path(lca(v_1, v_2), v_2)))$$$ $$$\Leftrightarrow xor(path(lca(v_1, v_2), v_1)) = xor(path(lca(v_1, v_2), v_2)) \Rightarrow$$$ Satisfy the condition</p><p>So here is what I do:</p> <ol> <li>Let the edge between $$$r$$$ and $$$u$$$ have weight $$$1$$$.</li> <li>We dfs from $$$r$$$, save the prefix $$$xor$$$ value from $$$r$$$ to the node $$$p$$$ we are at and dfs to node children $$$v$$$ of $$$p$$$:</li> </ol> <ul> <li>If $$$v$$$ is a leaf, then we need to assign this edge so that the prefix $$$xor$$$ value will be equal to $$$1$$$ ($$$ = xor(path(r, u))$$$).</li> <li>If $$$v$$$ is not a leaf, then we assign $$$2$$$ to that edge. Why? Because we need to get rid of the case when the prefix $$$xor$$$ value at node $$$p$$$ (parent of leaf $$$v$$$, for example) is equal to $$$1$$$ ($$$ = xor(path(r, u))$$$) and whatever we assign $$$edge(p, v)$$$ we cannot make the prefix $$$xor$$$ value at leaf $$$v$$$ equal to $$$1$$$ anymore.</li> </ul><p>P/s: Ask me anything that you may not understand ^^. </p></div> </div> </div> <div class="reply info"> <a class="comment-602348 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602348 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602348"> <li> <div class="comment"> <table class="comment-table" commentId="602440" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602440" href="?#comment-602440" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602440" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602440"> <div class="moveup"> <div class="ttypography"><p>Thanks!</p><p>Now I think the key observation to come up with all of this is the parity of distances of three leafs.</p><p>$$$parity(dist(l1,l2)) \oplus parity(dist(l1,l3)) = parity(dist(l2,l3))$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-602440 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602440 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602440"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603442" commentParentId="602348"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603442" href="?#comment-603442" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602348" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603442" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603442"> <div class="moveup"> <div class="ttypography"><p>I didnt get the part where you assign 2 to the edge that is not a leaf.</p></div> </div> </div> <div class="reply info"> <a class="comment-603442 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603442 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603442"> <li> <div class="comment"> <table class="comment-table" commentId="603446" commentParentId="603442"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603446" href="?#comment-603446" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603442" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603446"> <div class="moveup"> <div class="ttypography"><p>Consider all the edges which not connect any leaf are assigned $$$2$$$, then all the prefix $$$xor$$$ value at node $$$p$$$ (not a leaf) will be either $$$...000$$$ or $$$...010$$$. So when we go to a leaf we can assign a possible value to make the prefix $$$xor$$$ equal to $$$...001$$$. </p><p>Suppose we don't assign $$$2$$$ but $$$1$$$ or $$$3$$$ then there will be the case when at node $$$p$$$ (not a leaf but have a leaf child) the prefix $$$xor$$$ may be $$$...001$$$ and go to node $$$v$$$ (the leaf child of $$$p$$$) whether we assign the edge $$$1$$$, $$$2$$$ or $$$3$$$ then the prefix $$$xor$$$ can't be $$$...001$$$ anymore.</p><p>Sorry for my bad English !</p></div> </div> </div> <div class="reply info"> <a class="comment-603446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603446"> <li> <div class="comment"> <table class="comment-table" commentId="603451" commentParentId="603446"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/viswanathtadi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/viswanathtadi" title="Pupil viswanathtadi" class="rated-user user-green">viswanathtadi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603451" href="?#comment-603451" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603446" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603451" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1437475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603451"> <div class="moveup"> <div class="ttypography"><p>Thanks to your quick reply,I am able to understand it.Can you please suggest some resources or something that would help me in solving problem cause' I am only able to solve upto problem c everytime?</p></div> </div> </div> <div class="reply info"> <a class="comment-603451 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603451 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603451"> <li> <div class="comment"> <table class="comment-table" commentId="603456" commentParentId="603451"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HynDuf" style="position: relative;"> <img src='https://userpic.codeforces.org/795140/avatar/b89a013be391a3e9.jpg'/> </a> <div><a href="/profile/HynDuf" title="Master HynDuf" class="rated-user user-orange">HynDuf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 06:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603456" href="?#comment-603456" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603451" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603456" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="795140" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603456"> <div class="moveup"> <div class="ttypography"><p>My suggestions: Solve problems and reflect upon what you have done wrong ... or what's observation you missed (And note them back obviously) ... or new algorithms (search and read for them and do 3 — 5 problems about that topic). Sometimes algorithm have signs, try to see that.</p><p>P/s: It's my own opinion anyway. Good luck &lt;3.</p></div> </div> </div> <div class="reply info"> <a class="comment-603456 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603456 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603456"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606855" commentParentId="602042"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Darooha" style="position: relative;"> <img src='https://userpic.codeforces.org/27157/avatar/c4be2a4212ec87ed.jpg'/> </a> <div><a href="/profile/Darooha" title="Pupil Darooha" class="rated-user user-green">Darooha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 17:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606855" href="?#comment-606855" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606855" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="27157" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-606855"> <div class="moveup"> <div class="ttypography"><p>To everybody: The editorial has this update. It makes the problem much simpler:</p><p>(Update) There is an another way to approach, provided by Darooha.</p><p>If you label vertices instead of edges where all leaves have same label and none of neighbors have same label, then you can consider edge weight as xor of two vertices' labels, so this is basically equivalent to original problem.</p><p>Now for minimum, you can see that labelling 0 to leaves, and 1,2 to non-leaves are enough, so you can prove minimum value of f is at most 3. In same manner, you can try parity checking to check if f value can be 1 or not.</p><p>For maximum, assign 0 to all leaves and assign all different values(21,22,...) to non-leaf vertices, then you can see all edge weights(except leaves connected to same vertex) are different.</p></div> </div> </div> <div class="reply info"> <a class="comment-606855 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606855 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606855"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rojansudev700" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rojansudev700" title="Newbie rojansudev700" class="rated-user user-gray">rojansudev700</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 20:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602066" href="?#comment-602066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1236502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602066"> <div class="moveup"> <div class="ttypography"><p>Can anybody please explain problem A and its editorial?</p></div> </div> </div> <div class="reply info"> <a class="comment-602066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602066"> <li> <div class="comment"> <table class="comment-table" commentId="602098" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602098" href="?#comment-602098" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602098"> <div class="moveup"> <div class="ttypography"><p>You may refer to the picture in the editorial. In this picture, if you put the red one in, you will find there is only one way to fill it( also described in the picture). Hence, since there are N different ways for putting the red one in, the answer is simply N.</p></div> </div> </div> <div class="reply info"> <a class="comment-602098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602098"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602157" commentParentId="602066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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="Apr/12/2020 21:33">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602157" href="?#comment-602157" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602157" 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-602157"> <div class="moveup"> <div class="ttypography"><p>Consider you want to find the answer for shape with size N. Let's say you put a Vertical diamond initially then places of all other diamonds are decided. So this is 1 way to put diamonds.</p><p>The other way is to put two horizontal diamonds on top left and bottom left and then we are have to find ways to puts diamonds in a shape of size N-1.</p><p>Ans(i) = 1 + Ans(i-1) <br /> {1 for the way in which vertical diamond is placed on the leftmost position}</p><p>Ans(i) = 1 + Ans(i-1) = i, given ans(1) =1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602157"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602093" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bayweiheng" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bayweiheng" title="Grandmaster bayweiheng" class="rated-user user-red">bayweiheng</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602093" href="?#comment-602093" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602093" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="533715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602093"> <div class="moveup"> <div class="ttypography"><p>In Div1E, How can we calculate the contribution from vertices with no indegree? If v has no indegree, then dis(u,v) is known but how do we find dis(v,u)? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-602093 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602093 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602093"> <li> <div class="comment"> <table class="comment-table" commentId="602110" commentParentId="602093"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602110" href="?#comment-602110" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602093" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602110" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602110"> <div class="moveup"> <div class="ttypography"><p>If $$$u$$$ has no in-degree then $$$dis(u,v)=1, dis(v,u)=614n$$$ for all $$$u\neq v$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602110 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602110 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602110"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602145" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Benq" style="position: relative;"> <img src='https://userpic.codeforces.org/312472/avatar/5716ac69aea8159a.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602145" href="?#comment-602145" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602145" 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="602145" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="312472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602145"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">E intuition?</b><div class="spoiler-content" style="display: none;"><p>Assume that all nodes have positive in-degree. Then we can arrange the nodes in a cycle $$$c_0,c_1,\ldots, c_{n-1}$$$ such that $$$c_i$$$ has edges to $$$c_{i+1},c_{i+2},\ldots,c_{(i+out(i))\pmod{n}}$$$ where $$$out(i)$$$ denotes the out-degree of node $$$c_i$$$. To find this cycle, start with any vertex $$$x$$$ and topologically sort $$$in(x)$$$. Then repeat with the last node of $$$in(x)$$$ (with respect to the sorted order).</p><p>For all $$$i$$$, $$$out(i)&gt;0$$$ and $$$out(i)\le out((i+1)\pmod{n})+1$$$. Suppose that $$$i&lt;j$$$. Then $$$out(i)+i\le out(j)+j$$$ and the distance from $$$c_j$$$ to $$$c_i$$$ is three iff $$$out(i)+i=out(j)+j$$$. Otherwise, it's one or two.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-602145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602145"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602151" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misqwerty" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/misqwerty" title="Newbie misqwerty" class="rated-user user-gray">misqwerty</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602151" href="?#comment-602151" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602151" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="727011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602151"> <div class="moveup"> <div class="ttypography"><p>Do anyone else other than me recognize this submission as a hack for a hack and there were two successful hacking attempts. That's a <strong>cheat</strong>. <a href="/contest/1339/submission/76401969" title="Submission 76401969 by SIBshaan">76401969</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602151 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602151 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602151"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602165" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602165" href="?#comment-602165" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602165" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602165"> <div class="moveup"> <div class="ttypography"><p>how to find editorial in english for Atcoder Begginer contest 162 on their website it's in japanese..</p></div> </div> </div> <div class="reply info"> <a class="comment-602165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602165"> <li> <div class="comment"> <table class="comment-table" commentId="602170" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:39">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602170" href="?#comment-602170" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602170" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602170"> <div class="moveup"> <div class="ttypography"><p>Pay attention to the red line written on the first page of the Japanese editorial .</p></div> </div> </div> <div class="reply info"> <a class="comment-602170 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602170 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602170"> <li> <div class="comment"> <table class="comment-table" commentId="602195" commentParentId="602170"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602195" href="?#comment-602195" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602170" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602195" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602195"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602195 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602195 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602195"> <li> <div class="comment"> <table class="comment-table" commentId="602248" commentParentId="602195"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602248" href="?#comment-602248" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602195" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602248" 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-602248"> <div class="moveup"> <div class="ttypography"><p>I've solved A,B,C,D if you want, i can tell u how to solve them</p></div> </div> </div> <div class="reply info"> <a class="comment-602248 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602248 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602248"> <li> <div class="comment"> <table class="comment-table" commentId="602255" commentParentId="602248"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602255" href="?#comment-602255" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602248" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602255" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602255" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602255"> <div class="moveup"> <div class="ttypography"><p>please tell me how you solved D</p></div> </div> </div> <div class="reply info"> <a class="comment-602255 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602255 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602255"> <li> <div class="comment"> <table class="comment-table" commentId="602270" commentParentId="602255"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602270" href="?#comment-602270" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602255" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602270" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602270" 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-602270"> <div class="moveup"> <div class="ttypography"><p>So you gonna fix i and k such that S[i] != S[k]. So in the range [i + 1, k — 1] you should find the number of characters C different from S[i] as well as S[j]. So, for example, if S[i] = 'R' and S[k] = 'G', C = 'B'. So these different characters can be found using segment tree, maybe there is other method too. Also you should check for the second condition, if (k — i) % 2 == 0 and S[(i + k) / 2] == c, you gonna decrement that number by one.</p></div> </div> </div> <div class="reply info"> <a class="comment-602270 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602270 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602270"> <li> <div class="comment"> <table class="comment-table" commentId="602272" commentParentId="602270"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/12/2020 23:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602272" href="?#comment-602272" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602270" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602272" 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-602272"> <div class="moveup"> <div class="ttypography"><p>That's my solution, but I think there is a better solution described in the following video: <a href="https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s">https://www.youtube.com/watch?v=IOy1GtYLMJA&amp;t=290s</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602272"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602172" commentParentId="602165"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fried-chicken" style="position: relative;"> <img src='https://userpic.codeforces.org/875027/avatar/afcc4cda915d2faa.jpg'/> </a> <div><a href="/profile/fried-chicken" title="Master fried-chicken" class="rated-user user-orange">fried-chicken</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602172" href="?#comment-602172" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602165" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602172" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="875027" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602172"> <div class="moveup"> <div class="ttypography"><p>Btw, why ask this here xD</p></div> </div> </div> <div class="reply info"> <a class="comment-602172 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602172 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602172"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602167" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602167" href="?#comment-602167" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602167" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602167"> <div class="moveup"> <div class="ttypography"><p>Could someone elaborate a bit more the intuition behind Div1D and how to implement it?</p></div> </div> </div> <div class="reply info"> <a class="comment-602167 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602167 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602167"> <li> <div class="comment"> <table class="comment-table" commentId="602265" commentParentId="602167"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602265" href="?#comment-602265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602167" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602265" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602265" class="CommentVoteFrame" data-commentRating="42" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+42</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602265"> <div class="moveup"> <div class="ttypography"><p>I approached this problem by considering what happens if we only consider the minimum connected subgraph containing the answer, where the answer is the set of nodes $$$S$$$ that form the nested rubber bands. First, consider each $$$v\in S$$$ as a circle, so we have $$$|S|$$$ nested circles. The other vertices of this minimum connected subgraph must contribute to connecting two or more circles, and we can consider them as line segments. </p><p>Colour the line segments red and the circles blue. Then, we'll see that the red vertices lie on a path, because we can trace out a path in this alternate representation of the tree. Furthermore, the blue vertices form an independent set, and each is adjacent to at least one red vertex.</p><p>DP states:</p><p>For each state, I suppose that the red vertices lie on a path in the subtree rooted at u with one endpoint at u.</p> <ul> <li><p>take[u] = number of blue vertices if u is blue</p></li> <li><p>skip[u] = number of blue vertices if u is red</p></li> </ul><p>DP transitions:</p> <ul> <li><p><code>take[u] = max(1 + skip[child])</code>. Since we're interested in a path, we take the max.</p></li> <li><p><code>skip[u] = max(#children-1 + max(take[child], skip[child]))</code>. If we colour u red, then we can colour all its uncoloured neighbours blue, but we still want to be able to choose for the next node in the path.</p></li> </ul><p>To get the answer, consider a path rooted at u. We need to know the best two values of <code>take[child]</code> and <code>max(take[child], skip[child])</code> to find the answer for such a path.</p><p>I'm sure you could fit the dp and get the solution in one dfs function, but here's my rather long and verbose code: <a href="https://codeforces.com/contest/1338/submission/76420228">https://codeforces.com/contest/1338/submission/76420228</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602265"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602182" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gouravmajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1380497/avatar/470f8f4adfac9b5d.jpg'/> </a> <div><a href="/profile/gouravmajee" title="Newbie gouravmajee" class="rated-user user-gray">gouravmajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602182" href="?#comment-602182" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602182" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1380497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602182"> <div class="moveup"> <div class="ttypography"><p>this was my first contest :) I passed question 1. </p></div> </div> </div> <div class="reply info"> <a class="comment-602182 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602182 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602182"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602191" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aid" style="position: relative;"> <img src='https://userpic.codeforces.org/106240/avatar/ab90218e19d9e731.jpg'/> </a> <div><a href="/profile/aid" title="International Grandmaster aid" class="rated-user user-red">aid</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 21:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602191" href="?#comment-602191" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602191" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="106240" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602191"> <div class="moveup"> <div class="ttypography"><p>$$$O(n^2\log(n))$$$ can be squeezed in E: <a href="/contest/1338/submission/76419686" title="Submission 76419686 by aid">76419686</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-602191 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602191 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602191"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602210" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cdc.biobot" style="position: relative;"> <img src='https://userpic.codeforces.org/152957/avatar/23e3d83914fae0f6.jpg'/> </a> <div><a href="/profile/cdc.biobot" title="Newbie cdc.biobot" class="rated-user user-gray">cdc.biobot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602210" href="?#comment-602210" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602210" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602210" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="152957" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602210"> <div class="moveup"> <div class="ttypography"><p>I beg your pardon, but I think problem statement of div2A should have been a bit clearer in explaining the term 'covering differently'. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-602210 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602210 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602210"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spharish" style="position: relative;"> <img src='https://userpic.codeforces.org/121318/avatar/d760aa07af4d6c61.jpg'/> </a> <div><a href="/profile/spharish" title="Pupil spharish" class="rated-user user-green">spharish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602211" href="?#comment-602211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602211" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="121318" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602211"> <div class="moveup"> <div class="ttypography"><p>In Div2 D for finding the maximum f value, what is the proof that there is no other construction possible that can possibly have more distinct weights? For example, consider a tree with the non-leaf nodes having degree 4. In the observation 3 picture, we can add to node 2, a replica structure of its child node 3. That will make node 2's degree 4. How to prove for this case(and in general) that the maximum value of f will not exceed e-l+m?</p></div> </div> </div> <div class="reply info"> <a class="comment-602211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602211"> <li> <div class="comment"> <table class="comment-table" commentId="602241" commentParentId="602211"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:09">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602241" href="?#comment-602241" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602211" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602241" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602241"> <div class="moveup"> <div class="ttypography"><p>Because that's the upper bound of the value.</p><p>Every edge that isn't adjacent to a leaf doesn't matter. Edges for leaves that are adjacent to the same non-leaf vertex need to be equal. That can be counted as in the editorial because — (leaves — non-leaf vertex adjacent to a leaf) is exactly the number of edges to leaves that are free to receive values.</p></div> </div> </div> <div class="reply info"> <a class="comment-602241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602241"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602221" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/johnathan_wick" style="position: relative;"> <img src='https://userpic.codeforces.org/1269203/avatar/80818ab48ba17cb6.jpg'/> </a> <div><a href="/profile/johnathan_wick" title="Newbie johnathan_wick" class="rated-user user-gray">johnathan_wick</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 22:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602221" href="?#comment-602221" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602221" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1269203" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602221"> <div class="moveup"> <div class="ttypography"><p>hi..what is the maximum time in which it's good to solve div2 — A and B.. because i'm practicing only DIV2 A and B question in virtual contest..and still took more than 1 h to solve both...some time i failed to solve B.. Thanks in advance..</p></div> </div> </div> <div class="reply info"> <a class="comment-602221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602221"> <li> <div class="comment"> <table class="comment-table" commentId="602497" commentParentId="602221"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602497" href="?#comment-602497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602221" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602497"> <div class="moveup"> <div class="ttypography"><p>See this round was tough, but I think top coders take max 15 min for both, at my rating I think even 30 mins would be fine and for you, 45-60 min is the max you should ideally take</p></div> </div> </div> <div class="reply info"> <a class="comment-602497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602497"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602236" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Muhammad98" style="position: relative;"> <img src='https://userpic.codeforces.org/697747/avatar/2c13087bfd195af6.jpg'/> </a> <div><a href="/profile/Muhammad98" title="Specialist Muhammad98" class="rated-user user-cyan">Muhammad98</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602236" href="?#comment-602236" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="697747" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602236"> <div class="moveup"> <div class="ttypography"><p>The only Div2A that I couldn't solve during the round XD</p></div> </div> </div> <div class="reply info"> <a class="comment-602236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602236"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602238" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602238" href="?#comment-602238" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602238" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+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-602238"> <div class="moveup"> <div class="ttypography"><p>Nice editorial and pictures! <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a> One suggestion: It'll be easier to read d1E if you use lowercase letters for vertices and upper case letters for sets.</p></div> </div> </div> <div class="reply info"> <a class="comment-602238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602238"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/gjaiswal108" style="position: relative;"> <img src='https://userpic.codeforces.org/756634/avatar/f398cd162ff7d60f.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/gjaiswal108" title="Expert gjaiswal108" class="rated-user user-blue">gjaiswal108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:21">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602251" href="?#comment-602251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602251" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756634" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602251"> <div class="moveup"> <div class="ttypography"><p><code>If you OEIS this, then you may find you can use Nimber Arithmetic to solve this</code></p><p>Can anyone tell me what is meaning of OEIS in the story of D2E ?</p></div> </div> </div> <div class="reply info"> <a class="comment-602251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602251"> <li> <div class="comment"> <table class="comment-table" commentId="602259" commentParentId="602251"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/blitzitout" style="position: relative;"> <img src='https://userpic.codeforces.org/505681/avatar/39b2976ffc156007.jpg'/> </a> <div><a href="/profile/blitzitout" title="Expert blitzitout" class="rated-user user-blue">blitzitout</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602259" href="?#comment-602259" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602251" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602259" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602259" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="505681" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602259"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/">This</a> is where you can find insights/recurrences of random sequences.</p></div> </div> </div> <div class="reply info"> <a class="comment-602259 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602259 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602259"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602252" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T-REXX" style="position: relative;"> <img src='https://userpic.codeforces.org/455170/avatar/f7f08af680e3156f.jpg'/> </a> <div><a href="/profile/T-REXX" title="Pupil T-REXX" class="rated-user user-green">T-REXX</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/12/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602252" href="?#comment-602252" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602252" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="455170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602252"> <div class="moveup"> <div class="ttypography"><p>I tried solving div2C by iterating through the array, whenever a[i]&gt;a[i+1] I added to all j=i+1 and j&lt;n lowest power of 2 possible to make it a[i]&lt;=a[i+1]. Lowest power was calculated using a vector of powers of 2. But it does not work, and I am unable to find out why. Can anyone help?</p></div> </div> </div> <div class="reply info"> <a class="comment-602252 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602252 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602252"> <li> <div class="comment"> <table class="comment-table" commentId="602471" commentParentId="602252"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bryceShakeair" style="position: relative;"> <img src='https://userpic.codeforces.org/872528/avatar/f8595cfd5dbfc474.jpg'/> </a> <div><a href="/profile/bryceShakeair" title="Specialist bryceShakeair" class="rated-user user-cyan">bryceShakeair</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602471" href="?#comment-602471" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602252" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602471" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872528" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602471"> <div class="moveup"> <div class="ttypography"><p>try 1 0 1 0 1 0 The optimal answer is x = 1 i.e. select indexes 2 , 4 ,6 you get 1 1 1 1 1 1 I hope that is clear </p></div> </div> </div> <div class="reply info"> <a class="comment-602471 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602471 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602471"> <li> <div class="comment"> <table class="comment-table" commentId="604684" commentParentId="602471"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604684" href="?#comment-604684" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602471" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604684" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604684"> <div class="moveup"> <div class="ttypography"><p>Thanks. </p></div> </div> </div> <div class="reply info"> <a class="comment-604684 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604684 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604684"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602282" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant_raja" style="position: relative;"> <img src='https://userpic.codeforces.org/742080/avatar/101f3740a4030218.jpg'/> </a> <div><a href="/profile/nishant_raja" title="Pupil nishant_raja" class="rated-user user-green">nishant_raja</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602282" href="?#comment-602282" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602282" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742080" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602282"> <div class="moveup"> <div class="ttypography"><p>Can anyone briefly explain the problem &quot;Powered Addition&quot;, I mean full approach and walk through an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-602282 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602282 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602282"> <li> <div class="comment"> <table class="comment-table" commentId="602498" commentParentId="602282"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jbs1jbs1jbs1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/jbs1jbs1jbs1" title="Specialist jbs1jbs1jbs1" class="rated-user user-cyan">jbs1jbs1jbs1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602498" href="?#comment-602498" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602282" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602498" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1308333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602498"> <div class="moveup"> <div class="ttypography"><p>My approach was as follows:</p><p>Let's say that the list is <code>[1, 7, 6, 5]</code>. We go through and we look at all the pairs <code>(a[i], a[i+1])</code>. We start with <code>(1,7)</code>. It satisfies the property of being non-decreasing, so we do nothing. Next, we go to <code>(7, 6)</code>. <code>6 &lt; 7</code>, meaning we have to add something to &quot;6&quot; to make it bigger. I assert (and will explain below the reason why), that it is possible and optimal to convert the &quot;6&quot; into a &quot;7&quot;. The list then becomes <code>[1, 7, 7, 5]</code>. Next, we look at the final pair <code>(7, 5)</code> and do the same: convert the &quot;5&quot; to a &quot;7&quot;, so that the final list becomes [1, 7, 7, 7].</p><p>When we convert a pair (a, b) to the pair (a, a), it means that we need to add some quantity (a-b) to it. If that quantity is 18, for example, then we can do this with 16 + 2 = 2^4 + 2^1. If that quantity is 15, we can do this with 2^0 + 2^1 + 2^2 + 2^3. In general, there is exactly one way to do the addition of distinct powers of 2 to get from one number to another.</p><p>You can find out which powers of 2 you need to add together by converting the difference into binary. The definition of binary is that where there is a &quot;1&quot; you can add the relevant power of 2.</p><p>In any case, I'm just saying that it is always <strong>possible</strong> to do this, and it doesn't matter what the exact powers of 2 are, you just need to know what the biggest power of 2 needed will be. This is because if you're using a bigger power of 2, for example 2^5, it means that seconds 1, 2, 3, 4, 5, 6 have already happened, so you could have, in the past, added 2^0, 2^1, 2^2, 2^3, 2^4 if you needed to do so.</p><p>The biggest power of 2 needed can be worked out by taking the logarithm base 2 of the difference, and then rounding down.</p><p>The code would then be something like this:</p> <pre><code>max_power_found = -1 for i in range(len(a) - 1): if a[i + 1] &lt; a[i]: difference = a[i] - a[i + 1] biggest_power = floor(log2(difference)) max_power_found = max(max_power_found, biggest_power) a[i + 1] = a[i] print(max_power_found + 1) </code></pre><p>Note that I initialise <code>max_power_found</code> to <code>-1</code> so that at the end, if nothing has happened because the array was already non-decreasing, it becomes <code>0</code> when you add 1.</p><p>Note also that even though we don't need to output the final array, I have the line <code>a[i + 1] = a[i]</code>. This is because the next pair needs to know about the change we just made.</p><p>There are <code>(n-1)</code> possible values of <code>i</code>, and for each one we do some constant time computation (logarithm base 2 is very fast), this is an O(n) solution.</p><p>Note that even if you didn't know about logarithms, you could probably do it very quickly because log2(10^5) is very small (though I haven't tested to make sure this doesn't TLE):</p> <pre><code>def biggest_power_needed(difference): # Outputs -1 if difference is 0. answer = -1 total = 0 while total &lt; difference: answer++ total += pow(2, answer) if total == difference: return answer else: return answer - 1 </code></pre><p>Again, we do <code>answer - 1</code> because we can use the smaller powers of 2 to increase it to exactly equal the difference.</p></div> </div> </div> <div class="reply info"> <a class="comment-602498 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602498 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602498"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shivamsaluja20" style="position: relative;"> <img src='https://userpic.codeforces.org/820036/avatar/92e6360dd7bc5c3d.jpg'/> </a> <div><a href="/profile/shivamsaluja20" title="Specialist shivamsaluja20" class="rated-user user-cyan">shivamsaluja20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 00:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602291" href="?#comment-602291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602291" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="820036" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602291"> <div class="moveup"> <div class="ttypography"><p>For the first time for problem A, it took me around 50 minutes to figure out and ironically that was the easiest one liner solution possible. Take the input and print it xD.</p></div> </div> </div> <div class="reply info"> <a class="comment-602291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EleCursity" style="position: relative;"> <img src='https://userpic.codeforces.org/388600/avatar/c667ca12cb3a5eb2.jpg'/> </a> <div><a href="/profile/EleCursity" title="Expert EleCursity" class="rated-user user-blue">EleCursity</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602292" href="?#comment-602292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602292" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="388600" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602292"> <div class="moveup"> <div class="ttypography"><p>Nice Editorial and nice problems. In <strong>div2E/div1C</strong> .I've found a strange pattern for the bits in the n-th triple . but I can't manage to code it during the contest. this is my code <a href="/contest/1339/submission/76432679" title="Submission 76432679 by EleCursity">76432679</a> .</p></div> </div> </div> <div class="reply info"> <a class="comment-602292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602297" href="?#comment-602297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602297"> <div class="moveup"> <div class="ttypography"><p>2D, I understand nothing, damn constructive problems and damn gap between C and D</p><p>&quot;Observation 1. You can prove that minimum value of f is at most 3, by following construction;&quot;</p><p>Well, how do we know there is no other construction where we would have 4 or more?</p><p>&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?</p><p>&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose</p></div> </div> </div> <div class="reply info"> <a class="comment-602297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602297"> <li> <div class="comment"> <table class="comment-table" commentId="602302" commentParentId="602297"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 01:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602302" href="?#comment-602302" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602297" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602302" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-602302"> <div class="moveup"> <div class="ttypography"><p>&quot;Well, how do we know there is no other construction where we would have 4 or more?&quot; The problem is asking for the minimum, there is a construction where $$$3$$$ is possible so the minimum is never greater than $$$3$$$</p><p>&quot;&quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>Why?&quot; Because we decided that that's how the construction should look like. Another example of a construction which would work is edges connecting a leaf having a weight of $$$2$$$ or $$$3$$$ depending on the parity leaf's depth and all other edges having a weight of $$$1$$$.</p><p>&quot;&quot;Because if f=2 then there should be even number of edges for each weight&quot;</p><p>Why? There should be some proof by contradiction I suppose&quot; Here's a proof: Notice that we can consider each bit separately and then an assignment works if the condition is satisfied for all bits. Let's say we choose numbers $$$a$$$ and $$$b$$$. If both $$$a$$$ and $$$b$$$ have some bit set to $$$1$$$ then that is the same as the $$$f=1$$$ case. If there is no bit which both $$$a$$$ and $$$b$$$ have set to 1 then that means that there is a bit which $$$a$$$ has set to $$$1$$$ and $$$b$$$ has set to $$$0$$$ and that there is a bit which $$$a$$$ has set to $$$0$$$ and $$$b$$$ has set to $$$1$$$, so each path needs to have an even number of both $$$a$$$ and $$$b$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-602302 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602302 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602302"> <li> <div class="comment"> <table class="comment-table" commentId="602304" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 02:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602304" href="?#comment-602304" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602304" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602304"> <div class="moveup"> <div class="ttypography"><p>1-2) Oh, so it was about describing a generic technique of assigning values, not about the specific tree on the picture. Then it makes more sense</p><p>3) The confusing part here was that I thought it was about the number of a and b in the whole tree, not on the requested path, and didn't understand why.</p><p>I'll reread it with this in mind</p><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-602304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602304"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603392" commentParentId="602302"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WitchOfTruth" style="position: relative;"> <img src='https://userpic.codeforces.org/1380888/avatar/1c673e77c9a77f52.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/WitchOfTruth" title="Expert WitchOfTruth" class="rated-user user-blue">WitchOfTruth</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 02:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603392" href="?#comment-603392" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602302" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603392" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603392" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1380888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603392"> <div class="moveup"> <div class="ttypography"><p>I've got how we come up with f=3 from the comments</p><p>However I still don't understand the same part in the editorial &quot;Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not&quot;</p><p>On the picture we have a string of non-leaves, all of which have degree 3. And all the leaves obviously have degree 1 So following this statement we're supposed to have the same weights for every edge connecting a non-leaf to a leaf on the picture. However, this is not the case. </p></div> </div> </div> <div class="reply info"> <a class="comment-603392 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603392 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603392"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/feecIe6418" style="position: relative;"> <img src='https://userpic.codeforces.org/699680/avatar/da9b3b3e29a8fe7b.jpg'/> </a> <div><a href="/profile/feecIe6418" title="International Grandmaster feecIe6418" class="rated-user user-red">feecIe6418</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 03:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602320" href="?#comment-602320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602320" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="699680" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602320"> <div class="moveup"> <div class="ttypography"><p>Finally become master in this round. I like the problems! Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-602320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602334" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 04:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602334" href="?#comment-602334" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602334" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602334"> <div class="moveup"> <div class="ttypography"><p><strong>HELP! Please</strong></p><p>Hi, everyone! My friends has some trouble in his solutions, He has submitted this solution <a href="/contest/1339/submission/76367506" title="Submission 76367506 by zhouxiaolun">76367506</a> during the round, However, after the system pending test, He did not get an AC, but still the Pretest passed. The score for this problem was not added to my friends. He has submitted totally the same code just now, <a href="/contest/1339/submission/76438866" title="Submission 76438866 by zhouxiaolun">76438866</a>, and get an AC. Why did this happen? It has effected on my friends ratings, Where can I find the administor to solve the trouble? (sorry for my poor english)</p></div> </div> </div> <div class="reply info"> <a class="comment-602334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602334"> <li> <div class="comment"> <table class="comment-table" commentId="602339" commentParentId="602334"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iynaur87" style="position: relative;"> <img src='https://userpic.codeforces.org/561459/avatar/4516a52f8c97c0c2.jpg'/> </a> <div><a href="/profile/iynaur87" title="Candidate Master iynaur87" class="rated-user user-violet">iynaur87</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602339" href="?#comment-602339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602334" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602339" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="561459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602339"> <div class="moveup"> <div class="ttypography"><p>Weired. You can Send a message to <a href="https://codeforces.com/profile/MikeMirzayanov">https://codeforces.com/profile/MikeMirzayanov</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602339"> <li> <div class="comment"> <table class="comment-table" commentId="602345" commentParentId="602339"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goatzyq" style="position: relative;"> <img src='https://userpic.codeforces.org/1216909/avatar/97fbf6af90a5fa42.jpg'/> </a> <div><a href="/profile/goatzyq" title="Candidate Master goatzyq" class="rated-user user-violet">goatzyq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602345" href="?#comment-602345" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602339" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602345" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1216909" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602345"> <div class="moveup"> <div class="ttypography"><p>Thank you! You are so kind!</p></div> </div> </div> <div class="reply info"> <a class="comment-602345 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602345 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602345"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602341" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Raghu150999" style="position: relative;"> <img src='https://userpic.codeforces.org/714738/avatar/992860969ab6c84.jpg'/> </a> <div><a href="/profile/Raghu150999" title="Expert Raghu150999" class="rated-user user-blue">Raghu150999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 05:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602341" href="?#comment-602341" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602341" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714738" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602341"> <div class="moveup"> <div class="ttypography"><p>Great editorial. Thanks a lot!</p></div> </div> </div> <div class="reply info"> <a class="comment-602341 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602341 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602341"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602383" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aspiriner" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/aspiriner" title="Expert aspiriner" class="rated-user user-blue">aspiriner</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602383" href="?#comment-602383" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602383" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1393907" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602383"> <div class="moveup"> <div class="ttypography"><p>in the div 2 B </p><p>i do not understand what the 'Sort the list, and make an oscillation centered on middle element like picture below.' means.</p><p>i just dont know how to sort it and what should i do in the next step.</p><p>please help me!</p></div> </div> </div> <div class="reply info"> <a class="comment-602383 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602383 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602383"> <li> <div class="comment"> <table class="comment-table" commentId="602411" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shisuko" style="position: relative;"> <img src='https://userpic.codeforces.org/554313/avatar/42772b63e4542d29.jpg'/> </a> <div><a href="/profile/Shisuko" title="Candidate Master Shisuko" class="rated-user user-violet">Shisuko</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602411" href="?#comment-602411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602411" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="554313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602411"> <div class="moveup"> <div class="ttypography"><p>Sort the elements in ascending order. Then you go smallest-&gt;largest-&gt;second smallest-&gt;second largest... and so on. If you draw it on paper, you can see that the gaps are always getting smaller because it's a subset of the previous gap.</p></div> </div> </div> <div class="reply info"> <a class="comment-602411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602411"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602415" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Diegogrc" style="position: relative;"> <img src='https://userpic.codeforces.org/475760/avatar/a9bb20f8e6c3f1a6.jpg'/> </a> <div><a href="/profile/Diegogrc" title="International Master Diegogrc" class="rated-user user-orange">Diegogrc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602415" href="?#comment-602415" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602415" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="475760" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602415"> <div class="moveup"> <div class="ttypography"><p>Imagine the problem is the same, but differences between pairs must be non increasing instead of non decreasing ( | a_ i — a_i-1 | &gt;= | a_i-1 — a_i-2 | ). If we solve this, we can just reverse the answer and we will get an answer to the original problem. </p><p>Now, imagine we start with the biggest element to the left. What number should we add next to maximize their difference? The smallest element. So we add it. After that, what number not yet added would maximize the difference of the pair? The second biggest element, and it is not hard to see it will be smaller or equal than the first pair. If we continue to do this, we can get an answer.</p><p>So to build it we just sort the initial array and then build it in the following way: a[N] , a[1] , a[N-1] , a[2] , a[N-2] , a[3] ... </p><p>After this, don't forget to reverse the answer to solve the original problem. </p><p>Submission: <a href="/contest/1339/submission/76418078" title="Submission 76418078 by Diegogrc">76418078</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602415 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602415 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602415"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602445" commentParentId="602383"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xD." style="position: relative;"> <img src='https://userpic.codeforces.org/918251/avatar/298a43e5c9cee8f5.jpg'/> </a> <div><a href="/profile/xD." title="Pupil xD." class="rated-user user-green">xD.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 10:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602445" href="?#comment-602445" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602383" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602445" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602445" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="918251" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602445"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/aspiriner" title="Pupil aspiriner">aspiriner</a> <strong>This picture may help you</strong> <img alt=" " src="/predownloaded/43/9a/439a03f6fa84e1a1c14509dbd3d5c4c88ee8d5a3.php" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-602445 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602445 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602445"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602386" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/misty1999" style="position: relative;"> <img src='https://userpic.codeforces.org/461973/avatar/bda2e09a046c8571.jpg'/> </a> <div><a href="/profile/misty1999" title="Specialist misty1999" class="rated-user user-cyan">misty1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 07:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602386" href="?#comment-602386" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602386" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="461973" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602386"> <div class="moveup"> <div class="ttypography"><p>First I thought maximal independent set in div1D, but got Wrong Answer on pretest 4.</p></div> </div> </div> <div class="reply info"> <a class="comment-602386 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602386 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602386"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuber_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/820815/avatar/9d558886908a602d.jpg'/> </a> <div><a href="/profile/cuber_coder" title="Master cuber_coder" class="rated-user user-orange">cuber_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602400" href="?#comment-602400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602400" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="820815" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602400"> <div class="moveup"> <div class="ttypography"><p>Great problemset, a beautifully written editorial, no queueforces, strong pretests and quick system testing makes it a wonderful round! Hope to participate in more rounds authored by you in future!</p><p>P.S. : my most special round till date since I finally reached CM !</p></div> </div> </div> <div class="reply info"> <a class="comment-602400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602400"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602404" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602404" href="?#comment-602404" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602404" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602404"> <div class="moveup"> <div class="ttypography"><p>can someone explain div2-C,i am not able to understand the editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-602404 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602404 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602404"> <li> <div class="comment"> <table class="comment-table" commentId="602437" commentParentId="602404"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602437" href="?#comment-602437" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602404" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602437" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602437"> <div class="moveup"> <div class="ttypography"><p>first of all find the max difference between any two number (O(n)). then you just need to count number of digits in it. which can be done using log2 of that difference. note: ceil function is to be used for ex: 2.5 would be rounded off to 3.</p><p>here's my code(which is actually someone else but I copied it and modified a little, but is self explanatory )</p><p><a href="https://codeforces.com/contest/1339/submission/76446573">https://codeforces.com/contest/1339/submission/76446573</a></p></div> </div> </div> <div class="reply info"> <a class="comment-602437 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602437 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602437"> <li> <div class="comment"> <table class="comment-table" commentId="602494" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602494" href="?#comment-602494" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602494" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602494"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-green" href="/profile/FinalBoss_" title="Pupil FinalBoss_">FinalBoss_</a> Can you please explain why did you add 1 in log2(dis+1) ?</p><p>I guess dis is the max number required to add.Why +1 ?My first submission was same but i didnt add 1 it got wa.</p></div> </div> </div> <div class="reply info"> <a class="comment-602494 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602494 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602494"> <li> <div class="comment"> <table class="comment-table" commentId="602546" commentParentId="602494"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FinalBoss_" style="position: relative;"> <img src='https://userpic.codeforces.org/1213458/avatar/a3ebc4eb490706e7.jpg'/> </a> <div><a href="/profile/FinalBoss_" title="Pupil FinalBoss_" class="rated-user user-green">FinalBoss_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:16">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602546" href="?#comment-602546" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602494" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602546" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1213458" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602546"> <div class="moveup"> <div class="ttypography"><p>yes dis is the max number required to add. log2(dis+1) is done because... we were asked to find 2^(x-1).</p><p>in case all numbers are equal and dis is 0 or if array is already increasing and dis is still 0, then log(0) becomes undefined. Now since we don't need actual value but ceiling of it so adding 1 to dis and then taking log will have same effect but also it will remove ambiguity of log(0).</p></div> </div> </div> <div class="reply info"> <a class="comment-602546 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602546 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602546"> <li> <div class="comment"> <table class="comment-table" commentId="602650" commentParentId="602546"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/stranger006" style="position: relative;"> <img src='https://userpic.codeforces.org/872024/avatar/964675f94758df4a.jpg'/> </a> <div><a href="/profile/stranger006" title="Expert stranger006" class="rated-user user-blue">stranger006</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602650" href="?#comment-602650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602546" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872024" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602650"> <div class="moveup"> <div class="ttypography"><p>Thanks, got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-602650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602650"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="603609" commentParentId="602437"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vaibhavsingh100070" style="position: relative;"> <img src='https://userpic.codeforces.org/792197/avatar/6a8b6f989cc93e7d.jpg'/> </a> <div><a href="/profile/vaibhavsingh100070" title="Pupil vaibhavsingh100070" class="rated-user user-green">vaibhavsingh100070</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 09:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603609" href="?#comment-603609" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602437" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="603609" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="792197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603609"> <div class="moveup"> <div class="ttypography"><p>Can you please explain for this test case n = 5 a = [ 1, 2, 1, 4, 1] For this output is ** 2**. How in 2 steps we will make this array non decreasing?</p></div> </div> </div> <div class="reply info"> <a class="comment-603609 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603609 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603609"> <li> <div class="comment"> <table class="comment-table" commentId="604681" commentParentId="603609"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/back_to_code" style="position: relative;"> <img src='https://userpic.codeforces.org/1292092/avatar/b57b403a9af2ef26.jpg'/> </a> <div><a href="/profile/back_to_code" title="Specialist back_to_code" class="rated-user user-cyan">back_to_code</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 09:45">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604681" href="?#comment-604681" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-603609" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604681" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604681" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1292092" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604681"> <div class="moveup"> <div class="ttypography"><p>Same doubt. Hoping someone to answer.</p><p>Edit: Got it. Should have read the question carefully. It says select any indices not continuous indices.</p><p>for n=5 ans array [ 1 2 1 4 1 ] </p><p>Step 1: Select indices : Select 3 and 5 ( begins from 0) Step 2: Increase by 1 then by 2 ( 2^x-1 , put x=1 and then 2) So array becomes : 1 2 4 4 4 which is non-decreasing.</p></div> </div> </div> <div class="reply info"> <a class="comment-604681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604681"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 08:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602409" href="?#comment-602409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602409" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602409"> <div class="moveup"> <div class="ttypography"><p>I have doubt in 1339 B -Sorted Adjacent Differences: If the array is: -2 5 5 6 The answer will be 5 -2 5 6 which is wrong Please explain if i am wrong</p></div> </div> </div> <div class="reply info"> <a class="comment-602409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602409"> <li> <div class="comment"> <table class="comment-table" commentId="602428" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602428" href="?#comment-602428" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602428"> <div class="moveup"> <div class="ttypography"><p>it is wrong because the required condition is not fulfilled as your answer will make seqeunce like this 7&lt;=7&gt;1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602428"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602433" commentParentId="602409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mestu" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Mestu" title="Expert Mestu" class="rated-user user-blue">Mestu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602433" href="?#comment-602433" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602433" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="922247" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602433"> <div class="moveup"> <div class="ttypography"><p>For array -2 5 5 6 the answer will be 5 5 -2 6 </p></div> </div> </div> <div class="reply info"> <a class="comment-602433 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602433 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602433"> <li> <div class="comment"> <table class="comment-table" commentId="602473" commentParentId="602433"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jayshil" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Jayshil" title="Pupil Jayshil" class="rated-user user-green">Jayshil</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602473" href="?#comment-602473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602433" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1266472" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602473"> <div class="moveup"> <div class="ttypography"><p>yes,but according to tutorial it is printing 5-2 5 6</p></div> </div> </div> <div class="reply info"> <a class="comment-602473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602473"> <li> <div class="comment"> <table class="comment-table" commentId="602740" commentParentId="602473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 17:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602740" href="?#comment-602740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602740"> <div class="moveup"> <div class="ttypography"><p>according to tutorial it will print 5 5 -2 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-602740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602740"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602427" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/inazuma_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/inazuma_11" title="Newbie inazuma_11" class="rated-user user-gray">inazuma_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:27">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602427" href="?#comment-602427" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602427" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1335781" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602427"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain O(N) approach for div 2C ? I know how to do it in O(NlogN) but not in O(N)</p></div> </div> </div> <div class="reply info"> <a class="comment-602427 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602427 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602427"> <li> <div class="comment"> <table class="comment-table" commentId="602432" commentParentId="602427"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602432" href="?#comment-602432" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602427" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602432" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602432"> <div class="moveup"> <div class="ttypography"><p>While traversing the array keep a count of what maximum difference have you seen so far from the previous element i.e maximum value uptil that i minus the array value at that i. Then once you found the maximum difference than going for finding the position of the highest bit in this maximum difference. The ans is going to be the value of this highest bit + 1. Make sure to include the edge case that if the maximum difference is 0 then the ans is also 0.</p></div> </div> </div> <div class="reply info"> <a class="comment-602432 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602432 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602432"> <li> <div class="comment"> <table class="comment-table" commentId="602492" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602492" href="?#comment-602492" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602492" 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="602492" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602492"> <div class="moveup"> <div class="ttypography"><p>Here is my thinking about this problem, which is much easier to understand: Lets say we need T seconds to make array becoming non descending. On each seconds from 1 to T we can choose any set of numbers from array to add 2^(t-1). It means that for each element of the array, on each second, we have choice to add or not to add this power of 2. So it means we can choose ANY number to add to each of array element. So the question is now simple: what is the min number M so that if for each a[i] we choose some number from 0 up to M to add to it, we can make array non descending. I just go from left to right, if next a[i+1] is less than a[i] I increase it to be equal a[i].</p></div> </div> </div> <div class="reply info"> <a class="comment-602492 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602492 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602492"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602531" commentParentId="602432"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:57">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602531" href="?#comment-602531" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602432" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602531" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602531"> <div class="moveup"> <div class="ttypography"><p>why do we need to add the 1?</p></div> </div> </div> <div class="reply info"> <a class="comment-602531 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602531 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602531"> <li> <div class="comment"> <table class="comment-table" commentId="602549" commentParentId="602531"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div 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_Phenomenal" style="position: relative;"> <img src='https://userpic.codeforces.org/1361637/avatar/a530d3ca1b212389.jpg'/> </a> <div><a href="/profile/The_Phenomenal" title="Specialist The_Phenomenal" class="rated-user user-cyan">The_Phenomenal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 13:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602549" href="?#comment-602549" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602531" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602549" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1361637" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602549"> <div class="moveup"> <div class="ttypography"><p>because suppose the highest bit is 2 that will be 100 but the time this would have occurred will be 3 seconds(1,2,4). Due to this, we need to add 1 to the highest bit that we obtain.</p></div> </div> </div> <div class="reply info"> <a class="comment-602549 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602549 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602549"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602429" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/harsh_67" style="position: relative;"> <img src='https://userpic.codeforces.org/1434221/avatar/b095cc7c6c8e67d8.jpg'/> </a> <div><a href="/profile/harsh_67" title="Expert harsh_67" class="rated-user user-blue">harsh_67</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602429" href="?#comment-602429" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602429" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602429" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1434221" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602429"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain how the answer of this testcase in problem div2/probC is 3.</p><p>4 2 -1 -3 -4</p></div> </div> </div> <div class="reply info"> <a class="comment-602429 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602429 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602429"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 09:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602431" href="?#comment-602431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602431" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602431"> <div class="moveup"> <div class="ttypography"><p>For DIV2D, first root the tree at any leaf (here, leaf = vertex with degree 1), and note that the XOR sum along any root leaf path must be 0. Now, delete all the leaves and the edges that lead from the leaves to their parents. In this graph, to get maximum value of f, assign distinct powers of 2 to each edge. Then re-introduce the leaves and leaf-to-parent edges, and assign them weights such that XOR sum from root to leaf will be zero. Notice that the values assigned to these leaf-to-parent edges will be distinct unless two leaves share the same parents. Thus, the maximum value of f will be n — 1 — (lvs — p), where lvs = number of leaves in this tree and p = number of nodes which have exactly one child leaf.</p><p>To get minimum f, do the same thing above (root tree at any leaf, then delete leaves and all leaf-parent edges). Then, in this new graph, assign weight 2 to the edge incident on the root, and to all other edges assign weight 1. Now, reintroduce the leaves and the leaf-parent edges, and assign these edges weights such that XOR sum along the root leaf path is 0. Notice that you will only have to assign weights of either 2 or 3 to these edges. So f &lt;= 3. The only case left is to work out when f = 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-602431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602431"> <li> <div class="comment"> <table class="comment-table" commentId="602644" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zass" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zass" title="Expert zass" class="rated-user user-blue">zass</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 16:07">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602644" href="?#comment-602644" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602644" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="916405" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602644"> <div class="moveup"> <div class="ttypography"><p>In lvs is root considered one of the leaves and in p is the parent of the root considered as one among p when the parent of root only has root as its child?</p></div> </div> </div> <div class="reply info"> <a class="comment-602644 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602644 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602644"> <li> <div class="comment"> <table class="comment-table" commentId="602811" commentParentId="602644"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grandesonnerie" style="position: relative;"> <img src='https://userpic.codeforces.org/873736/avatar/97a6261e63ac7407.jpg'/> </a> <div><a href="/profile/grandesonnerie" title="Master grandesonnerie" class="rated-user user-orange">grandesonnerie</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602811" href="?#comment-602811" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602644" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602811" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="873736" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602811"> <div class="moveup"> <div class="ttypography"><p>In lvs, the root is not considered one of the leaves. And in p, parent of root is not included because root does not have a parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-602811 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602811 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602811"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="602798" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <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="Apr/13/2020 18:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602798" href="?#comment-602798" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602798" class="CommentVoteFrame" data-commentRating="5" 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;">+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-602798"> <div class="moveup"> <div class="ttypography"><p>Nice explanation but I read your code to understand fully. =)) Code is still the best explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-602798 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602798 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602798"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="650339" commentParentId="602431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rmaa" style="position: relative;"> <img src='https://userpic.codeforces.org/499170/avatar/6e864314e460334e.jpg'/> </a> <div><a href="/profile/rmaa" title="Expert rmaa" class="rated-user user-blue">rmaa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2020 23:47">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-650339" href="?#comment-650339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="650339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="499170" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-650339"> <div class="moveup"> <div class="ttypography"><p>Thanks so much, your explanation helped me understand this problem 2 months later! :) It's so mind-boggling to understand how one can come up with this construction in time during the contest.</p><p>The reason I want to post here is to add something to your solution in case anyone after me has the same question. (also to just solidify my own understanding) I actually had this question myself while reading — we know that the XOR from the root to all the different leaves must be zero. But how can one prove that the XOR from one leaf to another is also zero? (a path that does not include the root, but rather just two leaves in the tree?) After all we need to make EVERY path between leaves XOR to 0</p><p>The logic is quite simple. As we said before we know XOR of the paths from the root to the two leafs, call them L1 and L2, are both zero. These paths must share some similar segment (specifically its from the LCA(L1, L2) to the root). Call the XOR of this shared segment X. Then we know the XOR from the path from L1 to LCA(L1, L2) = X, and same with the path from L2 to LCA(L1, L2). Because if (x XOR y) = 0, then x = y, and the XOR of the whole path can be broken up the XOR of two segments L1 -&gt; LCA, LCA -&gt; root. (same with L2).</p><p>The editorial also explains this logic a bit but I hope what I wrote can help. </p></div> </div> </div> <div class="reply info"> <a class="comment-650339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-650339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-650339"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602484" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AgentCode" style="position: relative;"> <img src='https://userpic.codeforces.org/1166754/avatar/7266a4b7f774caa1.jpg'/> </a> <div><a href="/profile/AgentCode" title="Newbie AgentCode" class="rated-user user-gray">AgentCode</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602484" href="?#comment-602484" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="602484" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="602484" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1166754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602484"> <div class="moveup"> <div class="ttypography"><p>I cant understand the editorial of Powered Addition clearly.Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-602484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602484"> <li> <div class="comment"> <table class="comment-table" commentId="602493" commentParentId="602484"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vqt2" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/vqt2" title="Candidate Master vqt2" class="rated-user user-violet">vqt2</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 12:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602493" href="?#comment-602493" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602493" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1471885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602493"> <div class="moveup"> <div class="ttypography"><p>I just post my 2 cents above, hope it is easier to understand</p></div> </div> </div> <div class="reply info"> <a class="comment-602493 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602493 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602493"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602629" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ZeroNik" style="position: relative;"> <img src='https://userpic.codeforces.org/1336702/avatar/4935627333ab6d15.jpg'/> </a> <div><a href="/profile/ZeroNik" title="Pupil ZeroNik" class="rated-user user-green">ZeroNik</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602629" href="?#comment-602629" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602629" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1336702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602629"> <div class="moveup"> <div class="ttypography"><p>Who can explain problem A again. I don't undersatand why answer is n</p></div> </div> </div> <div class="reply info"> <a class="comment-602629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602629"> <li> <div class="comment"> <table class="comment-table" commentId="602636" commentParentId="602629"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/invincibel31" style="position: relative;"> <img src='https://userpic.codeforces.org/842069/avatar/78296878ae951a3.jpg'/> </a> <div><a href="/profile/invincibel31" title="Expert invincibel31" class="rated-user user-blue">invincibel31</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 15:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602636" href="?#comment-602636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602629" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="842069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602636"> <div class="moveup"> <div class="ttypography"><p>ans is equal to n bcz of the vertically standing diamonds in each way there will be only one diamond which would be standing vertically and since the number of diamond in n hence and in n</p></div> </div> </div> <div class="reply info"> <a class="comment-602636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602636"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602791" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hasnaine_" style="position: relative;"> <img src='https://userpic.codeforces.org/553185/avatar/dbae027ec9304551.jpg'/> </a> <div><a href="/profile/Hasnaine_" title="Expert Hasnaine_" class="rated-user user-blue">Hasnaine_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:23">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602791" href="?#comment-602791" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602791" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="553185" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602791"> <div class="moveup"> <div class="ttypography"><p><strong>Problem Div1(C), Div2(E):</strong> </p><p>Can anyone please elaborate on why this combination on bitmasking works?</p><p>Or, how to prove this combination works?</p><p>Thanks in advance. </p></div> </div> </div> <div class="reply info"> <a class="comment-602791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602791"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RedSnowstorm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RedSnowstorm" title="Expert RedSnowstorm" class="rated-user user-blue">RedSnowstorm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 18:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602796" href="?#comment-602796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602796" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="789793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-602796"> <div class="moveup"> <div class="ttypography"><p>Could someone please elaborate a bit more on Div1 C ? I understand the solution up to the first picture, but I don't understand neither the meaning of the second picture nor the rest of the solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-602796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602796"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="602873" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ateev_mishra7" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ateev_mishra7" title="Pupil ateev_mishra7" class="rated-user user-green">ateev_mishra7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-602873" href="?#comment-602873" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="602873" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174913" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-602873"> <div class="moveup"> <div class="ttypography"><p>Why does my solution to Div2-C is not working . <a href="https://codeforces.com/contest/1339/submission/76407068">https://codeforces.com/contest/1339/submission/76407068</a></p><p>can somebody please help me out on this .</p></div> </div> </div> <div class="reply info"> <a class="comment-602873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-602873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-602873"> <li> <div class="comment"> <table class="comment-table" commentId="603718" commentParentId="602873"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jsahil730" style="position: relative;"> <img src='https://userpic.codeforces.org/815806/avatar/511ed0e24b003ea4.jpg'/> </a> <div><a href="/profile/jsahil730" title="Expert jsahil730" class="rated-user user-blue">jsahil730</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603718" href="?#comment-603718" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-602873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603718" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603718" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="815806" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603718"> <div class="moveup"> <div class="ttypography"><p>Well let's take the sequence as 1 4 1 4, your code outputs 3 while it is supposed to output 2 since you can add 1 and 2 to the third element and get a sorted output.</p></div> </div> </div> <div class="reply info"> <a class="comment-603718 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603718 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603718"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="603291" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vyush" style="position: relative;"> <img src='https://userpic.codeforces.org/814106/avatar/d2c40519525d0732.jpg'/> </a> <div><a href="/profile/Vyush" title="Expert Vyush" class="rated-user user-blue">Vyush</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/13/2020 23:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-603291" href="?#comment-603291" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="603291" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="603291" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-603291"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain division1C/division2E I am not able to understand the approach in the editorial.I got the nim product observation but I don't know how to implement it also i don't get the editorials approach.If anyone could help that would be great.Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-603291 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-603291 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-603291"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604316" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sheaf" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sheaf" title="Expert sheaf" class="rated-user user-blue">sheaf</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 19:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604316" href="?#comment-604316" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604316" 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="604316" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="509827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604316"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, as for Div1E, isn't $$$R=in(P)\cap Q$$$, instead it is $$$R=in(V)\cap Q$$$? The latter just doesn't make sense if you consider the lemma 3. $$$in(V)$$$ is the subset of all vertices that have at least one outgoing edge, $$$in(P)\cap Q$$$ is the subset of all vertices of $$$Q$$$ that have at least one outgoing edge. Then lemma 3, which says there are edges from set $$$S$$$ to $$$R$$$, can't be true because it says that $$$S$$$ — a subset of $$$Q$$$ without outgoing edges — has edges pointing to $$$R$$$. On contrary, if we set $$$R=in(P)\cap Q$$$ we, can prove lemma 3 by forbidding the configuration from the statement. Also, can't really prove part of lemma 4 that says that $$$R$$$ has no cycles without it.</p></div> </div> </div> <div class="reply info"> <a class="comment-604316 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604316 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604316"> <li> <div class="comment"> <table class="comment-table" commentId="604403" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/14/2020 21:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604403" href="?#comment-604403" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604403" 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="604403" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604403"> <div class="moveup"> <div class="ttypography"><p>(erased)</p></div> </div> </div> <div class="reply info"> <a class="comment-604403 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604403 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604403"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604580" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 01:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604580" href="?#comment-604580" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604580" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="604580" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604580"> <div class="moveup"> <div class="ttypography"><p>oops, sorry, I understood your comment wrong. To be honest, I don't fully understand approach of this problem, so I would like to call author of this problem directly. <a class="rated-user user-legendary" href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></p></div> </div> </div> <div class="reply info"> <a class="comment-604580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604580"> <li> <div class="comment"> <table class="comment-table" commentId="604593" commentParentId="604580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:38">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604593" href="?#comment-604593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604593" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604593"> <div class="moveup"> <div class="ttypography"><p>Ugh, bad boy. You should be more responsible to your round.</p></div> </div> </div> <div class="reply info"> <a class="comment-604593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604593"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="604591" commentParentId="604316"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tzuyu_chou" style="position: relative;"> <img src='https://userpic.codeforces.org/744291/avatar/281708695a2703bd.jpg'/> </a> <div><a href="/profile/tzuyu_chou" title="Legendary Grandmaster tzuyu_chou" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>zuyu_chou</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 03:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604591" href="?#comment-604591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604316" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604591" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="744291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-604591"> <div class="moveup"> <div class="ttypography"><p>Oh, I didn't realise that I used the variable $$$V$$$ 2 times. Now I fixed it. When I said $$$in(V) \cap Q$$$ I refered to the $$$V$$$ in Lemma 2. Thanks for pointinh out my mistake.</p></div> </div> </div> <div class="reply info"> <a class="comment-604591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604591"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604631" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 07:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604631" href="?#comment-604631" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604631"> <div class="moveup"> <div class="ttypography"><p>Hi, <a class="rated-user user-violet" href="/profile/McDic" title="Candidate Master McDic">McDic</a>, how does observation 1 of edge weight problem work since the shape of tree is determined by input rather than can be arbitrary constructed as in observation 1? Take example input 3 for instance. Thanks in advance.</p></div> </div> </div> <div class="reply info"> <a class="comment-604631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604631"> <li> <div class="comment"> <table class="comment-table" commentId="604757" commentParentId="604631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604757" href="?#comment-604757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604757" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604757"> <div class="moveup"> <div class="ttypography"><p><img alt="ex1" src="/predownloaded/a2/a8/a2a877e5c47802fc77cb6bee8965a15f80b6e799.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You can see that we can make $$$f = 1$$$ in this tree anyway.</p></div> </div> </div> <div class="reply info"> <a class="comment-604757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604757"> <li> <div class="comment"> <table class="comment-table" commentId="605625" commentParentId="604757"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/happy15" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/happy15" title="Specialist happy15" class="rated-user user-cyan">happy15</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605625" href="?#comment-605625" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604757" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605625" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="104196" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605625"> <div class="moveup"> <div class="ttypography"><p>I must misunderstand your meaning, but doesn't f=2 in the graph since there are weight of 1 and 2?</p><p>Or do you mean that the edge on 7-4-3 could be equivalent to a single edge with weight of 3=weight(7,4) xor weight(4,3)=2 xor 1? Thus in this way the observation 1 can be applied?</p></div> </div> </div> <div class="reply info"> <a class="comment-605625 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605625 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605625"> <li> <div class="comment"> <table class="comment-table" commentId="605631" commentParentId="605625"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605631" href="?#comment-605631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605625" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605631" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605631"> <div class="moveup"> <div class="ttypography"><p>This picture shows how you can manage $$$f \le 3$$$ in this tree with first observation. By &quot; <em>You can see that we can make $$$f = 1$$$ in this tree any</em> &quot; I mean you can replace all weights $$$2$$$ to $$$1$$$ to make $$$f = 1$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-605631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605631"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="604739" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/karanbhatia116" style="position: relative;"> <img src='https://userpic.codeforces.org/872128/avatar/afb324a25af3a491.jpg'/> </a> <div><a href="/profile/karanbhatia116" title="Newbie karanbhatia116" class="rated-user user-gray">karanbhatia116</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 11:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604739" href="?#comment-604739" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="604739" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872128" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604739"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain me the second test case for Div1A/Div2C(<a href="/contest/1338/problem/A" title="Codeforces Round 633 (Div. 1)">1338A - Powered Addition</a>)?</p> <pre><code>Input: 6 3 1000000000 0 -1000000000 1 6 2 -1000000000 1000000000 2 1000000000 -1000000000 2 1000000000 1000000000 2 -1000000000 -1000000000 Output: 31 0 0 31 0 0 </code></pre><p>How is the output 31 and not 32? If it is 31 then we must have added 2^30 in 0 and -1000000000 but that does not make the array non-decreasing in the first test case.</p></div> </div> </div> <div class="reply info"> <a class="comment-604739 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604739 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604739"> <li> <div class="comment"> <table class="comment-table" commentId="604760" commentParentId="604739"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/15/2020 12:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-604760" href="?#comment-604760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-604739" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="604760" 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="604760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-604760"> <div class="moveup"> <div class="ttypography"><p>Select $$$2$$$-nd index at last second only, and $$$3$$$-rd index all the time. Then you get </p><p>$$$a = [10^{9}, 0, -10^{9}] \to [10^{9}, 0 + 2^{30}, -10^{9} + 2^{0} + 2^{1} + \ldots + 2^{30}] = [1000000000, 1073741824, 1147483647]$$$</p><p>So you can make $$$a$$$ non-decreasing in $$$31$$$ seconds.</p></div> </div> </div> <div class="reply info"> <a class="comment-604760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-604760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-604760"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605553" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 09:12">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605553" href="?#comment-605553" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605553" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605553"> <div class="moveup"> <div class="ttypography"><p>why does the answer for div2-C depends only on largest difference? Can someone explain in detailed manner i am unable to get the logic behind it.</p></div> </div> </div> <div class="reply info"> <a class="comment-605553 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605553 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605553"> <li> <div class="comment"> <table class="comment-table" commentId="605637" commentParentId="605553"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 11:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605637" href="?#comment-605637" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605553" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="605637" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="605637" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605637"> <div class="moveup"> <div class="ttypography"><p>Fact 1: $$$2^{0} + 2^{1} + \ldots + 2^{t-1} \lt 2^{t}$$$.</p><p>This means if you want to add something equal or bigger than $$$2^{t}$$$ on some position, then you should use more than $$$t$$$ seconds.</p><p>Fact 2: Required seconds is determined by maximum bit of difference.</p><p>From two facts you can observe that smaller difference leads to shorter time.</p><p>I will write few examples below;</p> <ul> <li>diff = 0 -&gt; 0 second</li> <li>diff = 1 -&gt; 1 second ($$$1 = 2^{0}$$$)</li> <li>diff = 2 -&gt; 2 seconds ($$$2 = 2^{1}$$$)</li> <li>diff = 3 -&gt; 2 seconds ($$$3 = 2^{0} + 2^{1}$$$)</li> <li>diff = 4 -&gt; 3 seconds ($$$4 = 2^{2}$$$)</li> <li>diff = 5 -&gt; 3 seconds ($$$5 = 2^{0} + 2^{2}$$$)</li> <li>diff = 6 -&gt; 3 seconds ($$$6 = 2^{1} + 2^{2}$$$)</li> <li>diff = 7 -&gt; 3 seconds ($$$7 = 2^{0} + 2^{1} + 2^{2}$$$)</li> <li>...</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-605637 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605637 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605637"> <li> <div class="comment"> <table class="comment-table" commentId="605676" commentParentId="605637"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardy_9795" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardy_9795" title="Expert hardy_9795" class="rated-user user-blue">hardy_9795</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 12:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605676" href="?#comment-605676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-605637" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1296059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605676"> <div class="moveup"> <div class="ttypography"><p>Thank you for your explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-605676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605676"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605607" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anshul23" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anshul23" title="Expert anshul23" class="rated-user user-blue">anshul23</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 10:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605607" href="?#comment-605607" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605607" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="551535" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-605607"> <div class="moveup"> <div class="ttypography"><p>Nice editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-605607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605607"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="605691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grapo_Oranges" style="position: relative;"> <img src='https://userpic.codeforces.org/1443313/avatar/3242fe30f43d5e9f.jpg'/> </a> <div><a href="/profile/grapo_Oranges" title="Expert grapo_Oranges" class="rated-user user-blue">grapo_Oranges</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/16/2020 13:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-605691" href="?#comment-605691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="605691" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443313" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-605691"> <div class="moveup"> <div class="ttypography"><p>@Anyone who solved Div2. D during the contest, can you explain how did you actually figure out the solution and was there any specific problem you ever did in past that helped you to solve this problem?</p></div> </div> </div> <div class="reply info"> <a class="comment-605691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-605691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-605691"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606212" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ankit_12" style="position: relative;"> <img src='https://userpic.codeforces.org/1461518/avatar/2c0c3df83d1920d2.jpg'/> </a> <div><a href="/profile/Ankit_12" title="Pupil Ankit_12" class="rated-user user-green">Ankit_12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 10:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606212" href="?#comment-606212" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="606212" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="606212" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1461518" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606212"> <div class="moveup"> <div class="ttypography"><p>Why this sequence is not correct for n=9, A/C to question Perfect Triples please Any one Help???</p><p>9 : 1 2 3 4 3 7 8 4 12</p></div> </div> </div> <div class="reply info"> <a class="comment-606212 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606212 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606212"> <li> <div class="comment"> <table class="comment-table" commentId="606260" commentParentId="606212"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 13:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606260" href="?#comment-606260" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606212" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606260" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606260"> <div class="moveup"> <div class="ttypography"><p>Because $$$3$$$ is used twice in your sequence.</p></div> </div> </div> <div class="reply info"> <a class="comment-606260 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606260 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606260"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="606777" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/striver_79" style="position: relative;"> <img src='https://userpic.codeforces.org/584222/avatar/92d0d608686eabcc.jpg'/> </a> <div><a href="/profile/striver_79" title="Candidate Master striver_79" class="rated-user user-violet">striver_79</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 13:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606777" href="?#comment-606777" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606777" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="584222" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606777"> <div class="moveup"> <div class="ttypography"><p>Video editorial for <a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div2D</a>/<a href="https://www.youtube.com/watch?v=YCOkesE_eN8">Div1B</a>: </p></div> </div> </div> <div class="reply info"> <a class="comment-606777 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606777 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606777"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607351" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/richikchanda1999" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/richikchanda1999" title="Pupil richikchanda1999" class="rated-user user-green">richikchanda1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 18:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607351" href="?#comment-607351" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607351" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="510979" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607351"> <div class="moveup"> <div class="ttypography"><p>Hey Codeforces,</p><p>Can anyone help me to come up with a better approach to the excluded problem (<a href="https://codeforces.com/gym/276159/problem/D1A_old">https://codeforces.com/gym/276159/problem/D1A_old</a>) apart from the brute-force approach which is giving TLE?</p></div> </div> </div> <div class="reply info"> <a class="comment-607351 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607351 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607351"> <li> <div class="comment"> <table class="comment-table" commentId="608851" commentParentId="607351"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/McDic" style="position: relative;"> <img src='https://userpic.codeforces.org/555986/avatar/28db2dd9a5096bd0.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/McDic" title="Candidate Master McDic" class="rated-user user-violet">McDic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/22/2020 18:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-608851" href="?#comment-608851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607351" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="608851" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="608851" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="555986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-608851"> <div class="moveup"> <div class="ttypography"><p>$$$x \oplus (x \cdot 2^{30}) = x \cdot (1 + 2^{30})$$$ if $$$x &lt; 2^{30}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-608851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-608851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-608851"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="619618" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/10/2020 21:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-619618" href="?#comment-619618" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="619618" 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="619618" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-619618"> <div class="moveup"> <div class="ttypography"><p>After a few weeks when I want to solve the problems I just realized the Editorial is so beautiful, those well-illustrated pictures and interesting stories made the Editorial so great!</p><p>But I had problems solving D1E. I cannot figure out why the <strong>Lemma 3</strong> and <strong>Lemma 6a/b</strong> are correct (And of course the final observations). Can you give proofs for them?</p><p><strong>UPD: After asking others, now I understood. Anyway, thanks the great Editorial!</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-619618 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-619618 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-619618"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="620074" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/11/2020 17:25">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620074" href="?#comment-620074" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="620074" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620074"> <div class="moveup"> <div class="ttypography"><p>i found a crazy solution of div1B <a href="https://codeforces.com/contest/1338/submission/76346806">https://codeforces.com/contest/1338/submission/76346806</a> can anyone plz explain the logic</p></div> </div> </div> <div class="reply info"> <a class="comment-620074 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620074 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620074"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="630800" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shpvb" style="position: relative;"> <img src='https://userpic.codeforces.org/720608/avatar/3fa49fe2fc134d7b.jpg'/> </a> <div><a href="/profile/shpvb" title="Candidate Master shpvb" class="rated-user user-violet">shpvb</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/27/2020 13:06">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-630800" href="?#comment-630800" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="630800" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-630800"> <div class="moveup"> <div class="ttypography"><p>Can someone provide insight into the mathematical induction referred to in observation 2 of div1C (Perfect Triples)?</p></div> </div> </div> <div class="reply info"> <a class="comment-630800 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-630800 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-630800"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="792521" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Livu_sz" style="position: relative;"> <img src='https://userpic.codeforces.org/1922428/avatar/3153d345afda896c.jpg'/> </a> <div><a href="/profile/Livu_sz" title="Expert Livu_sz" class="rated-user user-blue">Livu_sz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/19/2021 06:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-792521" href="?#comment-792521" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="792521" 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="792521" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1922428" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-792521"> <div class="moveup"> <div class="ttypography"><p>B was tough</p></div> </div> </div> <div class="reply info"> <a class="comment-792521 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-792521 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-792521"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1064206" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sartq" style="position: relative;"> <img src='https://userpic.codeforces.org/3093050/avatar/ec7dcd19bb83efab.jpg'/> </a> <div><a href="/profile/sartq" title="Newbie sartq" class="rated-user user-gray">sartq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/01/2023 06:30">5 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1064206" href="?#comment-1064206" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1064206" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="3093050" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1064206"> <div class="moveup"> <div class="ttypography"><p>In div2B can we solve the problem using a hashMap, like storing the values of differences of array and their indexes?</p></div> </div> </div> <div class="reply info"> <a class="comment-1064206 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1064206 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1064206"> </ul> </div> <br/> <div id="editBox-82006" 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 firstPreview82006 = true; var lastPreviewContent82006 = ''; 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=82006] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=82006] 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-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-76444").click(function () { $.post("/data/topic/vote", {topicId: 76444, _tta: Codeforces.tta(), topicRevisionId: 184450, 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:28:37</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:'81288c53eb1e161c',t:'MTY5NjcwNjkxNy4zNTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1339A
1339
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$$$. Сколькими способами можно полностью покрыть поясоподобную область, состоящую из $$$4n-2$$$ треугольников, ромбами?</p><p>Ромб состоит из двух треугольников. Вы можете перемещать, вращать или переворачивать ромб, но вы не можете масштабировать его.</p><p>$$$2$$$ покрытия называются различными, если некоторые $$$2$$$ треугольника покрыты одним и тем же ромбом в одном из них, и различными в другом.</p><p>Пожалуйста, посмотрите на иллюстрации ниже для лучшего понимания.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fe1ad8b85bef7134b3bba5bc2c576643aef558dc.png" style="max-width: 100.0%;max-height: 100.0%;"/> Слева изображен ромб, которым вы будете заполнять область, а справа  — область, которую вы хотите заполнить.<p><img class="tex-graphics" src="https://espresso.codeforces.com/253cb03aef62ea2260f28f431e7e51c962b79f23.png" style="max-width: 100.0%;max-height: 100.0%;"/> Выше приведены области, для $$$n = 1, 2, 3, 4$$$. </p></center><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^{4}$$$)  — количество тестовых случаев.</p><p>Каждая из следующих $$$t$$$ строк содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^{9}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого теста выведите количество способов полностью покрыть поясоподобную область, состоящую из $$$4n-2$$$ треугольников, ромбами. Можно показать, что при данных ограничениях это количество не превышает $$$10^{18}$$$.</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере, есть следующие $$$2$$$ способа заполнить область:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e72f8c635d8dc8aff12edac5df922a9410645cbb.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором тестовом примере, существует единственный способ заполнить область:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/076644b16c11b7a034b789a88ccaf85e52dd0102.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="15e505dddc2e4f08a131c0b5b95cd5d6"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f937e2fc45d8cdbceb861abc46c3214e76649ead"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='15e505dddc2e4f08a131c0b5b95cd5d6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1339%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='15e505dddc2e4f08a131c0b5b95cd5d6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1339">Codeforces Round 633 (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='15e505dddc2e4f08a131c0b5b95cd5d6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1339/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='15e505dddc2e4f08a131c0b5b95cd5d6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590526"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='15e505dddc2e4f08a131c0b5b95cd5d6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590526"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10754" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Codeforces Round #633 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10761" resourceName="Codeforces Round #633 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1339">Задачи</a></li> <li><a href="/contest/1339/submit">Отослать</a></li> <li><a href="/contest/1339/my">Мои посылки</a></li> <li><a href="/contest/1339/status">Статус</a></li> <li><a href="/contest/1339/hacks">Взломы</a></li> <li><a href="/contest/1339/room/1">Комната</a></li> <li><a href="/contest/1339/standings">Положение</a></li> <li><a href="/contest/1339/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ee401a36d9359a12833187ccb07663618d495364"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$. Сколькими способами можно полностью покрыть поясоподобную область, состоящую из $$$4n-2$$$ треугольников, ромбами?</p><p>Ромб состоит из двух треугольников. Вы можете перемещать, вращать или переворачивать ромб, но вы не можете масштабировать его.</p><p>$$$2$$$ покрытия называются различными, если некоторые $$$2$$$ треугольника покрыты одним и тем же ромбом в одном из них, и различными в другом.</p><p>Пожалуйста, посмотрите на иллюстрации ниже для лучшего понимания.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fe1ad8b85bef7134b3bba5bc2c576643aef558dc.png" style="max-width: 100.0%;max-height: 100.0%;" /> Слева изображен ромб, которым вы будете заполнять область, а справа  — область, которую вы хотите заполнить.<p><img class="tex-graphics" src="https://espresso.codeforces.com/253cb03aef62ea2260f28f431e7e51c962b79f23.png" style="max-width: 100.0%;max-height: 100.0%;" /> Выше приведены области, для $$$n = 1, 2, 3, 4$$$. </p></center><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^{4}$$$)  — количество тестовых случаев.</p><p>Каждая из следующих $$$t$$$ строк содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^{9}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого теста выведите количество способов полностью покрыть поясоподобную область, состоящую из $$$4n-2$$$ треугольников, ромбами. Можно показать, что при данных ограничениях это количество не превышает $$$10^{18}$$$.</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере, есть следующие $$$2$$$ способа заполнить область:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e72f8c635d8dc8aff12edac5df922a9410645cbb.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором тестовом примере, существует единственный способ заполнить область:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/076644b16c11b7a034b789a88ccaf85e52dd0102.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:41</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e171a3e1498',t:'MTY5NjY2NTcwMS4yMDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\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", "\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", "*900"]
1339B
1339
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$$$ чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$.</p><p>Переставьте эти числа так, чтобы они удовлетворяли $$$|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$$$, где $$$|x|$$$ обозначает абсолютное значение $$$x$$$. Гарантируется, что для данных ограничений всегда можно найти такую перестановку.</p><p>Обратите внимание, что элементы в $$$a$$$ не обязательно попарно различны. Другими словами, некоторые элементы $$$a$$$ могут быть одинаковыми.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^{4}$$$)  — количество тестовых случаев.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ ($$$3 \le n \le 10^{5}$$$)  — длину массива $$$a$$$. Гарантируется, что сумма значений $$$n$$$ по всем тестовых случаях не превышает $$$10^{5}$$$.</p><p>Вторая строка каждого тестового случая содержит $$$n$$$ целых чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).</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> 2 6 5 -2 4 8 6 5 4 8 1 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 5 4 6 8 -2 1 2 4 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, для данной перестановки, мы имеем $$$|a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10$$$. Существуют также другие ответы, к примеру "<span class="tex-font-style-tt">5 4 5 6 -2 8</span>".</p><p>Во втором тестовом случае, для данной перестановки, мы имеем $$$|a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4$$$. Существуют также другие ответы, к примеру "<span class="tex-font-style-tt">2 4 8 1</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="00b4238da6453d9f962cf791e1a8177b"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f937e2fc45d8cdbceb861abc46c3214e76649ead"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='00b4238da6453d9f962cf791e1a8177b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1339%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='00b4238da6453d9f962cf791e1a8177b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1339">Codeforces Round 633 (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='00b4238da6453d9f962cf791e1a8177b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1339/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='00b4238da6453d9f962cf791e1a8177b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590527"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='00b4238da6453d9f962cf791e1a8177b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590527"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10754" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Codeforces Round #633 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10761" resourceName="Codeforces Round #633 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1339">Задачи</a></li> <li><a href="/contest/1339/submit">Отослать</a></li> <li><a href="/contest/1339/my">Мои посылки</a></li> <li><a href="/contest/1339/status">Статус</a></li> <li><a href="/contest/1339/hacks">Взломы</a></li> <li><a href="/contest/1339/room/1">Комната</a></li> <li><a href="/contest/1339/standings">Положение</a></li> <li><a href="/contest/1339/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_443b4eb23a2e97757d980b121e019beb99c7cebc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$.</p><p>Переставьте эти числа так, чтобы они удовлетворяли $$$|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$$$, где $$$|x|$$$ обозначает абсолютное значение $$$x$$$. Гарантируется, что для данных ограничений всегда можно найти такую перестановку.</p><p>Обратите внимание, что элементы в $$$a$$$ не обязательно попарно различны. Другими словами, некоторые элементы $$$a$$$ могут быть одинаковыми.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^{4}$$$)  — количество тестовых случаев.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ ($$$3 \le n \le 10^{5}$$$)  — длину массива $$$a$$$. Гарантируется, что сумма значений $$$n$$$ по всем тестовых случаях не превышает $$$10^{5}$$$.</p><p>Вторая строка каждого тестового случая содержит $$$n$$$ целых чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).</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> 2 6 5 -2 4 8 6 5 4 8 1 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 5 4 6 8 -2 1 2 4 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, для данной перестановки, мы имеем $$$|a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10$$$. Существуют также другие ответы, к примеру &quot;<span class="tex-font-style-tt">5 4 5 6 -2 8</span>&quot;.</p><p>Во втором тестовом случае, для данной перестановки, мы имеем $$$|a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4$$$. Существуют также другие ответы, к примеру &quot;<span class="tex-font-style-tt">2 4 8 1</span>&quot;.</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/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:42</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e2038ee7b47',t:'MTY5NjY2NTcwMi41MTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1200"]
1339C
1339
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>У вас есть массив $$$a$$$ длины $$$n$$$. Для каждого положительного числа $$$x$$$ в течение $$$x$$$-й секунды вы собираетесь выполнить следующую операцию:</p><ul> <li> Выберите несколько различных индексов $$$i_{1}, i_{2}, \ldots, i_{k}$$$, которые находятся в диапазоне от $$$1$$$ до $$$n$$$ включительно, и добавьте $$$2^{x-1}$$$ к каждой соответствующей позиции в $$$a$$$. Формально $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ для $$$j = 1, 2, \ldots, k$$$. <span class="tex-font-style-bf">Обратите внимание, что вы можете также не выбрать ни одного индекса.</span> </li></ul><p>Вы должны сделать $$$a$$$ неубывающим как можно быстрее. Найдите наименьшее число $$$T$$$ такое, что вы можете сделать массив неубывающим не позднее, чем через $$$T$$$ секунд.</p><p>Массив $$$a$$$ называется неубывающим, если и только если $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^{4}$$$)  — количество тестовых случаев.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^{5}$$$)  — длину массива $$$a$$$. Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превышает $$$10^{5}$$$.</p><p>Вторая строка каждого теста содержит $$$n$$$ целых чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).</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 4 1 7 6 5 5 1 2 3 4 5 2 0 -4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, если вы выберете индексы $$$3, 4$$$ на $$$1$$$-й секунде и $$$4$$$ на $$$2$$$-й секунде, то $$$a$$$ станет равным $$$[1, 7, 7, 8]$$$. Есть и другие способы сделать $$$a$$$ неубывающим за $$$2$$$ секунды, но вы не сделать его неубывающим быстрее.</p><p>Во втором тестовом случае $$$a$$$ уже неубывающий, поэтому ответ равен $$$0$$$.</p><p>В третьем тестовом случае, если вы ничего не сделаете в первые $$$2$$$ секунды и в течение $$$3$$$-й секунды выберете индекс $$$2$$$, $$$a$$$ станет равным $$$[0, 0]$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f955f8008335c385eee51beac4e7c373"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f937e2fc45d8cdbceb861abc46c3214e76649ead"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f955f8008335c385eee51beac4e7c373'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1339%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='f955f8008335c385eee51beac4e7c373'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1339">Codeforces Round 633 (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='f955f8008335c385eee51beac4e7c373'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1339/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='f955f8008335c385eee51beac4e7c373'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590528"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f955f8008335c385eee51beac4e7c373'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590528"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10754" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Codeforces Round #633 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10761" resourceName="Codeforces Round #633 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1339">Задачи</a></li> <li><a href="/contest/1339/submit">Отослать</a></li> <li><a href="/contest/1339/my">Мои посылки</a></li> <li><a href="/contest/1339/status">Статус</a></li> <li><a href="/contest/1339/hacks">Взломы</a></li> <li><a href="/contest/1339/room/1">Комната</a></li> <li><a href="/contest/1339/standings">Положение</a></li> <li><a href="/contest/1339/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_86085881c3b2b8ad6f6cdc3ec4bbff7c43e06010"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>У вас есть массив $$$a$$$ длины $$$n$$$. Для каждого положительного числа $$$x$$$ в течение $$$x$$$-й секунды вы собираетесь выполнить следующую операцию:</p><ul> <li> Выберите несколько различных индексов $$$i_{1}, i_{2}, \ldots, i_{k}$$$, которые находятся в диапазоне от $$$1$$$ до $$$n$$$ включительно, и добавьте $$$2^{x-1}$$$ к каждой соответствующей позиции в $$$a$$$. Формально $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ для $$$j = 1, 2, \ldots, k$$$. <span class="tex-font-style-bf">Обратите внимание, что вы можете также не выбрать ни одного индекса.</span> </li></ul><p>Вы должны сделать $$$a$$$ неубывающим как можно быстрее. Найдите наименьшее число $$$T$$$ такое, что вы можете сделать массив неубывающим не позднее, чем через $$$T$$$ секунд.</p><p>Массив $$$a$$$ называется неубывающим, если и только если $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^{4}$$$)  — количество тестовых случаев.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^{5}$$$)  — длину массива $$$a$$$. Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превышает $$$10^{5}$$$.</p><p>Вторая строка каждого теста содержит $$$n$$$ целых чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).</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 4 1 7 6 5 5 1 2 3 4 5 2 0 -4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае, если вы выберете индексы $$$3, 4$$$ на $$$1$$$-й секунде и $$$4$$$ на $$$2$$$-й секунде, то $$$a$$$ станет равным $$$[1, 7, 7, 8]$$$. Есть и другие способы сделать $$$a$$$ неубывающим за $$$2$$$ секунды, но вы не сделать его неубывающим быстрее.</p><p>Во втором тестовом случае $$$a$$$ уже неубывающий, поэтому ответ равен $$$0$$$.</p><p>В третьем тестовом случае, если вы ничего не сделаете в первые $$$2$$$ секунды и в течение $$$3$$$-й секунды выберете индекс $$$2$$$, $$$a$$$ станет равным $$$[0, 0]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:43</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e286b849d3f',t:'MTY5NjY2NTcwMy45NzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1500"]
1339D
1339
D
ru
D. Назначение весов ребрам
<div class="problem-statement"><div class="header"><div class="title">D. Назначение весов ребрам</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть невзвешенное дерево на $$$n$$$ вершинах. Вы должны назначить <span class="tex-font-style-bf">положительный</span> вес каждому ребру, чтобы выполнялось следующее условие:</p><ul> <li> Для каждых двух разных листов $$$v_{1}$$$ и $$$v_{2}$$$ этого дерева, <a href="https://ru.wikipedia.org/wiki/Битовая_операция#Исключающее_ИЛИ">побитовое исключающее ИЛИ</a> весов всех ребер на простом пути между $$$v_{1}$$$ и $$$v_{2}$$$ должно быть равно $$$0$$$. </li></ul><p>Обратите внимание, что вы можете назначать <span class="tex-font-style-bf">очень большие</span> натуральные числа (такие как $$$10^{(10^{10})}$$$).</p><p>Гарантируется, что такое назначение всегда существует при данных ограничениях. Теперь определим $$$f$$$ как <span class="tex-font-style-bf">количество различных весов</span> среди назначенных весов.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/822324016e7a6837336849481ecbe0190b03dfa3.png" style="max-width: 100.0%;max-height: 100.0%;"/> В этом примере назначение верно, потому что побитовое исключающее ИЛИ всех весов ребер между каждой парой листьев равно $$$0$$$. Значение $$$f$$$ здесь равно $$$2$$$, потому что есть $$$2$$$ различных веса ребер ($$$4$$$ и $$$5$$$).<p><img class="tex-graphics" src="https://espresso.codeforces.com/82d52d5070be134d11729e65fab0a8709aae6b3f.png" style="max-width: 100.0%;max-height: 100.0%;"/> В этом примере назначение не удовлетворяет условию, поскольку побитовое исключающее ИЛИ всех весов ребер между вершинами $$$1$$$ и $$$6$$$ ($$$3, 4, 5, 4$$$) не равно $$$0$$$. </p></center><p>Чему равны минимальное и максимальное возможные значения $$$f$$$ для данного дерева? Найдите и выведите оба.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$3 \le n \le 10^{5}$$$)  — количество вершин в данном дереве.</p><p>$$$i$$$-я из следующих $$$n-1$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$)  — это означает, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Гарантируется, что данный граф образует дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа  — минимальное и максимальное возможное значения $$$f$$$, которые могут быть получены из правильного назначения данного дерева. Обратите внимание, что такое назначение всегда существует при данных ограничениях.</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 3 2 3 3 4 4 5 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 3 2 3 3 4 4 5 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 2 2 7 3 4 4 7 5 6 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере возможные назначения для минимума и максимума показаны на рисунке ниже. Конечно, есть и другие назначения. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e7bf97f0144ccdc05c3ef43ccaa89a3d0c9ce1dc.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором примере возможные назначения для минимума и максимума показаны на рисунке ниже. Значение $$$f$$$ для правильного назначения этого дерева всегда равно $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f98bbf02e8b21aed9fd5a82be44c2dcd71808c3c.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В третьем примере возможные назначения для минимума и максимума показаны на рисунке ниже. Конечно, есть и другие назначения. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0a99edbccedea10ea506d2c7bd3d027a4bdf17ce.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="d827031c2d35febfc52053d8b84405a0"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f937e2fc45d8cdbceb861abc46c3214e76649ead"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d827031c2d35febfc52053d8b84405a0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1339%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='d827031c2d35febfc52053d8b84405a0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1339">Codeforces Round 633 (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='d827031c2d35febfc52053d8b84405a0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1339/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='d827031c2d35febfc52053d8b84405a0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590529"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d827031c2d35febfc52053d8b84405a0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590529"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10754" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Codeforces Round #633 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10761" resourceName="Codeforces Round #633 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1339">Задачи</a></li> <li><a href="/contest/1339/submit">Отослать</a></li> <li><a href="/contest/1339/my">Мои посылки</a></li> <li><a href="/contest/1339/status">Статус</a></li> <li><a href="/contest/1339/hacks">Взломы</a></li> <li><a href="/contest/1339/room/1">Комната</a></li> <li><a href="/contest/1339/standings">Положение</a></li> <li><a href="/contest/1339/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_309658334cb7c34e35f9627906a9fc8db4fd3b32"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Назначение весов ребрам</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть невзвешенное дерево на $$$n$$$ вершинах. Вы должны назначить <span class="tex-font-style-bf">положительный</span> вес каждому ребру, чтобы выполнялось следующее условие:</p><ul> <li> Для каждых двух разных листов $$$v_{1}$$$ и $$$v_{2}$$$ этого дерева, <a href="https://ru.wikipedia.org/wiki/Битовая_операция#Исключающее_ИЛИ">побитовое исключающее ИЛИ</a> весов всех ребер на простом пути между $$$v_{1}$$$ и $$$v_{2}$$$ должно быть равно $$$0$$$. </li></ul><p>Обратите внимание, что вы можете назначать <span class="tex-font-style-bf">очень большие</span> натуральные числа (такие как $$$10^{(10^{10})}$$$).</p><p>Гарантируется, что такое назначение всегда существует при данных ограничениях. Теперь определим $$$f$$$ как <span class="tex-font-style-bf">количество различных весов</span> среди назначенных весов.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/822324016e7a6837336849481ecbe0190b03dfa3.png" style="max-width: 100.0%;max-height: 100.0%;" /> В этом примере назначение верно, потому что побитовое исключающее ИЛИ всех весов ребер между каждой парой листьев равно $$$0$$$. Значение $$$f$$$ здесь равно $$$2$$$, потому что есть $$$2$$$ различных веса ребер ($$$4$$$ и $$$5$$$).<p><img class="tex-graphics" src="https://espresso.codeforces.com/82d52d5070be134d11729e65fab0a8709aae6b3f.png" style="max-width: 100.0%;max-height: 100.0%;" /> В этом примере назначение не удовлетворяет условию, поскольку побитовое исключающее ИЛИ всех весов ребер между вершинами $$$1$$$ и $$$6$$$ ($$$3, 4, 5, 4$$$) не равно $$$0$$$. </p></center><p>Чему равны минимальное и максимальное возможные значения $$$f$$$ для данного дерева? Найдите и выведите оба.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$3 \le n \le 10^{5}$$$)  — количество вершин в данном дереве.</p><p>$$$i$$$-я из следующих $$$n-1$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$)  — это означает, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Гарантируется, что данный граф образует дерево из $$$n$$$ вершин.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа  — минимальное и максимальное возможное значения $$$f$$$, которые могут быть получены из правильного назначения данного дерева. Обратите внимание, что такое назначение всегда существует при данных ограничениях.</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 3 2 3 3 4 4 5 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 3 2 3 3 4 4 5 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 2 2 7 3 4 4 7 5 6 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере возможные назначения для минимума и максимума показаны на рисунке ниже. Конечно, есть и другие назначения. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e7bf97f0144ccdc05c3ef43ccaa89a3d0c9ce1dc.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере возможные назначения для минимума и максимума показаны на рисунке ниже. Значение $$$f$$$ для правильного назначения этого дерева всегда равно $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f98bbf02e8b21aed9fd5a82be44c2dcd71808c3c.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В третьем примере возможные назначения для минимума и максимума показаны на рисунке ниже. Конечно, есть и другие назначения. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0a99edbccedea10ea506d2c7bd3d027a4bdf17ce.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:45</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e318dcc7b17',t:'MTY5NjY2NTcwNS4zOTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\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", "*1800"]
1339E
1339
E
ru
E. Прекрасные тройки
<div class="problem-statement"><div class="header"><div class="title">E. Прекрасные тройки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим бесконечную последовательность $$$s$$$ натуральных чисел, построенную повторением следующих шагов:</p><ol> <li> Найдите лексикографически наименьшую тройку натуральных чисел $$$(a, b, c)$$$ такую, ​​что <ul> <li> $$$a \oplus b \oplus c = 0$$$, где $$$\oplus$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Битовая_операция#Исключающее_ИЛИ">побитовое исключающее ИЛИ</a>. </li><li> $$$a$$$, $$$b$$$, $$$c$$$ не находятся в $$$s$$$. </li></ul> Здесь тройка целых чисел $$$(a_1, b_1, c_1)$$$ считается лексикографически меньше тройки $$$(a_2, b_2, c_2)$$$, если последовательность $$$[a_1, b_1, c_1]$$$ лексикографически меньше последовательности $$$[a_2, b_2, c_2]$$$ </li><li> Добавьте $$$a$$$, $$$b$$$, $$$c$$$ в конец $$$s$$$ в этом порядке. </li><li> Вернитесь к первому шагу. </li></ol><p>У вас есть целое число $$$n$$$. Найдите $$$n$$$-й элемент $$$s$$$.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p><p>Последовательность $$$a$$$ лексикографически меньше последовательности $$$b$$$, если в первой позиции, где $$$a$$$ и $$$b$$$ различны, в последовательности $$$a$$$ элемент меньше, чем соответствующий элемент в $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$)  — количество тестовых случаев.</p><p>Каждая из следующих $$$t$$$ строк содержит одно целое число $$$n$$$ ($$$1\le n \le 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> 9 1 2 3 4 5 6 7 8 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 4 8 12 5 10 15 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые несколько элементов $$$s$$$ это $$$1, 2, 3, 4, 8, 12, 5, 10, 15, \dots $$$</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="670a935a3354242587fd1bde570ab1d5"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f937e2fc45d8cdbceb861abc46c3214e76649ead"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='670a935a3354242587fd1bde570ab1d5'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1339%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='670a935a3354242587fd1bde570ab1d5'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1339">Codeforces Round 633 (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='670a935a3354242587fd1bde570ab1d5'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1339/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='670a935a3354242587fd1bde570ab1d5'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="590530"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='670a935a3354242587fd1bde570ab1d5'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="590530"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/75806" title="Codeforces Round #633" target="_blank">Codeforces Round #633 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10754" resourceName="Codeforces Round #633" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/75913" title="Codeforces Round #633 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10761" resourceName="Codeforces Round #633 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1339">Задачи</a></li> <li><a href="/contest/1339/submit">Отослать</a></li> <li><a href="/contest/1339/my">Мои посылки</a></li> <li><a href="/contest/1339/status">Статус</a></li> <li><a href="/contest/1339/hacks">Взломы</a></li> <li><a href="/contest/1339/room/1">Комната</a></li> <li><a href="/contest/1339/standings">Положение</a></li> <li><a href="/contest/1339/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c64d947c845dd35dda0dba44413683c3242bbd32"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Прекрасные тройки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим бесконечную последовательность $$$s$$$ натуральных чисел, построенную повторением следующих шагов:</p><ol> <li> Найдите лексикографически наименьшую тройку натуральных чисел $$$(a, b, c)$$$ такую, ​​что <ul> <li> $$$a \oplus b \oplus c = 0$$$, где $$$\oplus$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Битовая_операция#Исключающее_ИЛИ">побитовое исключающее ИЛИ</a>. </li><li> $$$a$$$, $$$b$$$, $$$c$$$ не находятся в $$$s$$$. </li></ul> Здесь тройка целых чисел $$$(a_1, b_1, c_1)$$$ считается лексикографически меньше тройки $$$(a_2, b_2, c_2)$$$, если последовательность $$$[a_1, b_1, c_1]$$$ лексикографически меньше последовательности $$$[a_2, b_2, c_2]$$$ </li><li> Добавьте $$$a$$$, $$$b$$$, $$$c$$$ в конец $$$s$$$ в этом порядке. </li><li> Вернитесь к первому шагу. </li></ol><p>У вас есть целое число $$$n$$$. Найдите $$$n$$$-й элемент $$$s$$$.</p><p>Вы должны ответить на $$$t$$$ независимых тестовых случаев.</p><p>Последовательность $$$a$$$ лексикографически меньше последовательности $$$b$$$, если в первой позиции, где $$$a$$$ и $$$b$$$ различны, в последовательности $$$a$$$ элемент меньше, чем соответствующий элемент в $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$)  — количество тестовых случаев.</p><p>Каждая из следующих $$$t$$$ строк содержит одно целое число $$$n$$$ ($$$1\le n \le 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> 9 1 2 3 4 5 6 7 8 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 4 8 12 5 10 15 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первые несколько элементов $$$s$$$ это $$$1, 2, 3, 4, 8, 12, 5, 10, 15, \dots $$$</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/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:46</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e3a586c9d8a',t:'MTY5NjY2NTcwNi44MzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u041a\u043e\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"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\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", "*2200"]
1340A
1340
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></p><p>Оглядевшись вокруг, Денис подошел к незнакомцу и купил загадочный товар. Им оказался... Генератор случайных перестановок! Именно это мальчик так давно искал!</p><p>Придя домой он стал изучать, как работает его генератор и узнал алгоритм. Процесс генерации перестановки состоит из $$$n$$$ шагов. На $$$i$$$-м шаге выбирается позиция (индекс) для значения $$$i$$$ $$$(1 \leq i \leq n)$$$. Позиция для значения $$$i$$$ определяется следующим образом:</p><ul> <li> Для всех $$$j$$$ от $$$1$$$ до $$$n$$$ посчитаем $$$r_j$$$  — минимальный такой индекс, что $$$j \leq r_j \leq n$$$, a позиция $$$r_j$$$ еще не занята в перестановке. Если таких позиций нет, то будем считать, что значение $$$r_j$$$ не определено. </li><li> Для всех $$$t$$$ от $$$1$$$ до $$$n$$$ посчитаем $$$count_t$$$  — количество таких позиций $$$1 \leq j \leq n$$$, что значение $$$r_j$$$ определено и $$$r_j = t$$$. </li><li> Рассмотрим все еще не занятые позиции перестановки и среди таких рассмотрим позиции, для которых значение в массиве $$$count$$$ максимально. </li><li> Генератор выбирает одну из таких позиций для значения $$$i$$$. Генератор может выбрать <span class="tex-font-style-bf">любую</span> позицию. </li></ul><p>Рассмотрим работу алгоритма на следующем примере:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/15abb96c35071a49b2b1acdf0082b04b54f18bd6.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Пусть $$$n = 5$$$ и алгоритм уже расставил значения $$$1, 2, 3$$$ в перестановке. Рассмотрим, как генератор будет выбирать позицию для значения $$$4$$$:</p><ul> <li> Значения $$$r$$$ будут $$$r = [3, 3, 3, 4, \times]$$$, где $$$\times$$$ означает неопределенное значение. </li><li> Тогда значения $$$count$$$ будут $$$count = [0, 0, 3, 1, 0]$$$. </li><li> Есть только две не занятые позиции в перестановке: $$$3$$$ и $$$4$$$. Значение в массиве $$$count$$$ для позиции $$$3$$$ равно $$$3$$$, для позиции $$$4$$$ равно $$$1$$$. </li><li> Максимальное значение достигается только для позиции $$$3$$$, поэтому алгоритм однозначно выберет эту позицию для значения $$$4$$$. </li></ul><p>Довольный своим приобретением Денис пошел домой. Несколько дней без перерыва он генерировал перестановки и решил, что преисполнился в осознании процесса генерации. Он считает, что может придумывать случайные перестановки не хуже генератора. </p><p>После этого он выписал первую пришедшую на ум перестановку $$$p_1, p_2, \ldots, p_n$$$ и решил узнать, могла ли она получится в результате работы генератора.</p><p>К сожалению, эта задача оказалась слишком сложна для него, и он обратился за помощью к вам. Нужно определить, могла ли получиться выписанная перестановка применением описанного алгоритма, если генератор всегда выбирает нужную Денису позицию.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ $$$(1 \leq t \leq 10^5)$$$  — количество наборов входных данных в тесте. Далее содержатся сами описания наборов.</p><p>В первой строке каждого набора находится единственное целое число $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — длина перестановки.</p><p>Во второй строке набора находится $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$)  — выписанная Денисом перестановка.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем входным данным не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">Yes</span>», если эта перестановка могла быть получена в результате работы генератора. В противном случае выведите «<span class="tex-font-style-tt">No</span>».</p><p>Все буквы можно выводить в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 2 3 4 5 1 1 1 3 1 3 2 4 4 2 3 1 5 1 5 2 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes No Yes No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Промоделируем работу генератора на первом тесте.</p><p>На $$$1$$$ шаге $$$r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$$$. Максимальное значение достигается в любой свободной позиции, поэтому генератор может выбрать случайную позицию от $$$1$$$ до $$$5$$$. В нашем примере он выбрал $$$5$$$.</p><p>На $$$2$$$ шаге $$$r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]$$$. Максимальное значение достигается в позициях от $$$1$$$ до $$$4$$$, поэтому генератор может выбрать случайную позицию среди них. В нашем примере он выбрал $$$1$$$.</p><p>На $$$3$$$ шаге $$$r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]$$$. Максимальное значение равно $$$2$$$ и достигается только в позиции $$$2$$$, поэтому генератор выберет эту позицию.</p><p>На $$$4$$$ шаге $$$r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]$$$. Максимальное значение равно $$$3$$$ и достигается только в позиции $$$3$$$, поэтому генератор выберет эту позицию.</p><p>На $$$5$$$ шаге $$$r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]$$$. Максимальное значение равно $$$4$$$ и достигается только в позиции $$$4$$$, поэтому генератор выберет эту позицию.</p><p>Итого мы получили перестановку $$$2, 3, 4, 5, 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="1fec182c70e7a76fbb1ff3a59b2f4ba1"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f3dd79f93448a3ad2b44a4c080be0e4ea78af171"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='1fec182c70e7a76fbb1ff3a59b2f4ba1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1340%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='1fec182c70e7a76fbb1ff3a59b2f4ba1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1340">Codeforces Round 637 (Div. 1) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='1fec182c70e7a76fbb1ff3a59b2f4ba1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1340/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='1fec182c70e7a76fbb1ff3a59b2f4ba1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599365"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1fec182c70e7a76fbb1ff3a59b2f4ba1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599365"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10795:10796" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10811" resourceName="Codeforces Round #637 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1340">Задачи</a></li> <li><a href="/contest/1340/submit">Отослать</a></li> <li><a href="/contest/1340/my">Мои посылки</a></li> <li><a href="/contest/1340/status">Статус</a></li> <li><a href="/contest/1340/hacks">Взломы</a></li> <li><a href="/contest/1340/room/1">Комната</a></li> <li><a href="/contest/1340/standings">Положение</a></li> <li><a href="/contest/1340/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_af5e98f572f092818298ee75556f07ff82be8a19"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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></p><p>Оглядевшись вокруг, Денис подошел к незнакомцу и купил загадочный товар. Им оказался... Генератор случайных перестановок! Именно это мальчик так давно искал!</p><p>Придя домой он стал изучать, как работает его генератор и узнал алгоритм. Процесс генерации перестановки состоит из $$$n$$$ шагов. На $$$i$$$-м шаге выбирается позиция (индекс) для значения $$$i$$$ $$$(1 \leq i \leq n)$$$. Позиция для значения $$$i$$$ определяется следующим образом:</p><ul> <li> Для всех $$$j$$$ от $$$1$$$ до $$$n$$$ посчитаем $$$r_j$$$  — минимальный такой индекс, что $$$j \leq r_j \leq n$$$, a позиция $$$r_j$$$ еще не занята в перестановке. Если таких позиций нет, то будем считать, что значение $$$r_j$$$ не определено. </li><li> Для всех $$$t$$$ от $$$1$$$ до $$$n$$$ посчитаем $$$count_t$$$  — количество таких позиций $$$1 \leq j \leq n$$$, что значение $$$r_j$$$ определено и $$$r_j = t$$$. </li><li> Рассмотрим все еще не занятые позиции перестановки и среди таких рассмотрим позиции, для которых значение в массиве $$$count$$$ максимально. </li><li> Генератор выбирает одну из таких позиций для значения $$$i$$$. Генератор может выбрать <span class="tex-font-style-bf">любую</span> позицию. </li></ul><p>Рассмотрим работу алгоритма на следующем примере:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/15abb96c35071a49b2b1acdf0082b04b54f18bd6.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Пусть $$$n = 5$$$ и алгоритм уже расставил значения $$$1, 2, 3$$$ в перестановке. Рассмотрим, как генератор будет выбирать позицию для значения $$$4$$$:</p><ul> <li> Значения $$$r$$$ будут $$$r = [3, 3, 3, 4, \times]$$$, где $$$\times$$$ означает неопределенное значение. </li><li> Тогда значения $$$count$$$ будут $$$count = [0, 0, 3, 1, 0]$$$. </li><li> Есть только две не занятые позиции в перестановке: $$$3$$$ и $$$4$$$. Значение в массиве $$$count$$$ для позиции $$$3$$$ равно $$$3$$$, для позиции $$$4$$$ равно $$$1$$$. </li><li> Максимальное значение достигается только для позиции $$$3$$$, поэтому алгоритм однозначно выберет эту позицию для значения $$$4$$$. </li></ul><p>Довольный своим приобретением Денис пошел домой. Несколько дней без перерыва он генерировал перестановки и решил, что преисполнился в осознании процесса генерации. Он считает, что может придумывать случайные перестановки не хуже генератора. </p><p>После этого он выписал первую пришедшую на ум перестановку $$$p_1, p_2, \ldots, p_n$$$ и решил узнать, могла ли она получится в результате работы генератора.</p><p>К сожалению, эта задача оказалась слишком сложна для него, и он обратился за помощью к вам. Нужно определить, могла ли получиться выписанная перестановка применением описанного алгоритма, если генератор всегда выбирает нужную Денису позицию.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ $$$(1 \leq t \leq 10^5)$$$  — количество наборов входных данных в тесте. Далее содержатся сами описания наборов.</p><p>В первой строке каждого набора находится единственное целое число $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — длина перестановки.</p><p>Во второй строке набора находится $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$)  — выписанная Денисом перестановка.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем входным данным не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">Yes</span>», если эта перестановка могла быть получена в результате работы генератора. В противном случае выведите «<span class="tex-font-style-tt">No</span>».</p><p>Все буквы можно выводить в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 2 3 4 5 1 1 1 3 1 3 2 4 4 2 3 1 5 1 5 2 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes No Yes No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Промоделируем работу генератора на первом тесте.</p><p>На $$$1$$$ шаге $$$r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$$$. Максимальное значение достигается в любой свободной позиции, поэтому генератор может выбрать случайную позицию от $$$1$$$ до $$$5$$$. В нашем примере он выбрал $$$5$$$.</p><p>На $$$2$$$ шаге $$$r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]$$$. Максимальное значение достигается в позициях от $$$1$$$ до $$$4$$$, поэтому генератор может выбрать случайную позицию среди них. В нашем примере он выбрал $$$1$$$.</p><p>На $$$3$$$ шаге $$$r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]$$$. Максимальное значение равно $$$2$$$ и достигается только в позиции $$$2$$$, поэтому генератор выберет эту позицию.</p><p>На $$$4$$$ шаге $$$r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]$$$. Максимальное значение равно $$$3$$$ и достигается только в позиции $$$3$$$, поэтому генератор выберет эту позицию.</p><p>На $$$5$$$ шаге $$$r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]$$$. Максимальное значение равно $$$4$$$ и достигается только в позиции $$$4$$$, поэтому генератор выберет эту позицию.</p><p>Итого мы получили перестановку $$$2, 3, 4, 5, 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/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:48</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e435baf2de6',t:'MTY5NjY2NTcwOC4yMjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1500"]
1340B
1340
B
ru
B. Настя и табло
<div class="problem-statement"><div class="header"><div class="title">B. Настя и табло</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it"> Денис, справившийся с покупкой цветов и конфет (об этой истории вы узнаете в следующей задаче), поехал на встречу с Настей, чтобы предложить ей стать парой. </span></p><p><span class="tex-font-style-it"> И вот, они сидят вместе в кафе, болтают. Решительный Денис наконец-то предлагает быть им вместе, но... Но Настя не даёт никакого ответа. </span></p><p>Как же сильно расстроился бедный парень. Так сильно, что он пнул какое-то табло с цифрами. Цифры отображаются таким же образом, как на электронных часах: каждая позиция для цифры состоит из $$$7$$$ сегментов, которые могут быть включены или выключены, чтобы отображать различные цифры. На картинке показано, как изображаются все $$$10$$$ десятичных цифр: </p><center> <img class="tex-graphics" height="113px" src="https://espresso.codeforces.com/19e4ae06aceef4b9326d2ef6bca3339f5c84ed91.png" style="max-width: 100.0%;max-height: 100.0%;" width="378px"/> </center> После пинка некоторые палочки перестали работать, то есть некоторые палочки могли перестать гореть, если горели раньше. Но Денис запомнил, сколько палочек горело и сколько горит сейчас. Пусть сломалось <span class="tex-font-style-bf">ровно</span> $$$k$$$ палочек и известно, какие палочки горят сейчас. Денис задался вопросом: какое максимальное число может гореть на табло, если включить ровно $$$k$$$ палочек (из тех которые сейчас выключены)? <p><span class="tex-font-style-bf">Разрешается</span>, чтобы в числе были лидирующие нули.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано число $$$n$$$ $$$(1 \leq n \leq 2000)$$$  — количество цифр на табло и $$$k$$$ $$$(0 \leq k \leq 2000)$$$  — количество сломанных палочек.</p><p>В следующих $$$n$$$ строках находится по одной бинарной строке длины $$$7$$$, $$$i$$$-я из которых кодирует $$$i$$$-ю цифру табло.</p><p>Каждая цифра на табло состоит из $$$7$$$ палочек. Пронумеруем их, как на картинке ниже, и пусть на $$$i$$$-м месте бинарной строки будет $$$0$$$, если $$$i$$$-я палочка не горит и $$$1$$$, если горит. Тогда бинарная строка длины $$$7$$$ будет задавать то, какие палочки горят.</p><center> <img class="tex-graphics" height="265px" src="https://espresso.codeforces.com/bed1234ad2f319542a635519d6e40510e65f641b.png" style="max-width: 100.0%;max-height: 100.0%;" width="189px"/> </center><p>Таким образом, последовательности «1110111», «0010010», «1011101», «1011011», «0111010», «1101011», «1101111», «1010010», «1111111», «1111011» кодируют по порядку все цифры от $$$0$$$ до $$$9$$$ включительно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число, состоящее из $$$n$$$ разрядов – максимальное число, которое можно получить, если включить ровно $$$k$$$ палочек или $$$-1$$$, если невозможно так включить ровно $$$k$$$ палочек, чтобы на табло получилась какая-то последовательность цифр.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 7 0000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 5 0010010 0010010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 97</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 0100001 1001001 1010011 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте мы обязаны включить все $$$7$$$ палочек и получить на табло одну цифру $$$8$$$.</p><p>Во втором тесте у нас включены палочки таким образом, что образуются единицы. За $$$5$$$ дополнительно включённых палочек можно получить числа $$$07$$$, $$$18$$$, $$$34$$$, $$$43$$$, $$$70$$$, $$$79$$$, $$$81$$$ и $$$97$$$, из них выбираем максимальное  — $$$97$$$.</p><p>В третьем тесте невозможно так включить ровно $$$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="081339d8ec99b6d668a2ef99fa28734f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f3dd79f93448a3ad2b44a4c080be0e4ea78af171"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='081339d8ec99b6d668a2ef99fa28734f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1340%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='081339d8ec99b6d668a2ef99fa28734f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1340">Codeforces Round 637 (Div. 1) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='081339d8ec99b6d668a2ef99fa28734f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1340/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='081339d8ec99b6d668a2ef99fa28734f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599366"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='081339d8ec99b6d668a2ef99fa28734f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599366"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10795:10796" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10811" resourceName="Codeforces Round #637 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1340">Задачи</a></li> <li><a href="/contest/1340/submit">Отослать</a></li> <li><a href="/contest/1340/my">Мои посылки</a></li> <li><a href="/contest/1340/status">Статус</a></li> <li><a href="/contest/1340/hacks">Взломы</a></li> <li><a href="/contest/1340/room/1">Комната</a></li> <li><a href="/contest/1340/standings">Положение</a></li> <li><a href="/contest/1340/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b58b0a5354bb8b984eb1314d2dc8c9ddac4dc334"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Настя и табло</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it"> Денис, справившийся с покупкой цветов и конфет (об этой истории вы узнаете в следующей задаче), поехал на встречу с Настей, чтобы предложить ей стать парой. </span></p><p><span class="tex-font-style-it"> И вот, они сидят вместе в кафе, болтают. Решительный Денис наконец-то предлагает быть им вместе, но... Но Настя не даёт никакого ответа. </span></p><p>Как же сильно расстроился бедный парень. Так сильно, что он пнул какое-то табло с цифрами. Цифры отображаются таким же образом, как на электронных часах: каждая позиция для цифры состоит из $$$7$$$ сегментов, которые могут быть включены или выключены, чтобы отображать различные цифры. На картинке показано, как изображаются все $$$10$$$ десятичных цифр: </p><center> <img class="tex-graphics" height="113px" src="https://espresso.codeforces.com/19e4ae06aceef4b9326d2ef6bca3339f5c84ed91.png" style="max-width: 100.0%;max-height: 100.0%;" width="378px" /> </center> После пинка некоторые палочки перестали работать, то есть некоторые палочки могли перестать гореть, если горели раньше. Но Денис запомнил, сколько палочек горело и сколько горит сейчас. Пусть сломалось <span class="tex-font-style-bf">ровно</span> $$$k$$$ палочек и известно, какие палочки горят сейчас. Денис задался вопросом: какое максимальное число может гореть на табло, если включить ровно $$$k$$$ палочек (из тех которые сейчас выключены)? <p><span class="tex-font-style-bf">Разрешается</span>, чтобы в числе были лидирующие нули.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано число $$$n$$$ $$$(1 \leq n \leq 2000)$$$  — количество цифр на табло и $$$k$$$ $$$(0 \leq k \leq 2000)$$$  — количество сломанных палочек.</p><p>В следующих $$$n$$$ строках находится по одной бинарной строке длины $$$7$$$, $$$i$$$-я из которых кодирует $$$i$$$-ю цифру табло.</p><p>Каждая цифра на табло состоит из $$$7$$$ палочек. Пронумеруем их, как на картинке ниже, и пусть на $$$i$$$-м месте бинарной строки будет $$$0$$$, если $$$i$$$-я палочка не горит и $$$1$$$, если горит. Тогда бинарная строка длины $$$7$$$ будет задавать то, какие палочки горят.</p><center> <img class="tex-graphics" height="265px" src="https://espresso.codeforces.com/bed1234ad2f319542a635519d6e40510e65f641b.png" style="max-width: 100.0%;max-height: 100.0%;" width="189px" /> </center><p>Таким образом, последовательности «1110111», «0010010», «1011101», «1011011», «0111010», «1101011», «1101111», «1010010», «1111111», «1111011» кодируют по порядку все цифры от $$$0$$$ до $$$9$$$ включительно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число, состоящее из $$$n$$$ разрядов – максимальное число, которое можно получить, если включить ровно $$$k$$$ палочек или $$$-1$$$, если невозможно так включить ровно $$$k$$$ палочек, чтобы на табло получилась какая-то последовательность цифр.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 7 0000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 5 0010010 0010010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 97</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 0100001 1001001 1010011 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте мы обязаны включить все $$$7$$$ палочек и получить на табло одну цифру $$$8$$$.</p><p>Во втором тесте у нас включены палочки таким образом, что образуются единицы. За $$$5$$$ дополнительно включённых палочек можно получить числа $$$07$$$, $$$18$$$, $$$34$$$, $$$43$$$, $$$70$$$, $$$79$$$, $$$81$$$ и $$$97$$$, из них выбираем максимальное  — $$$97$$$.</p><p>В третьем тесте невозможно так включить ровно $$$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/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:49</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e4c1f779d45',t:'MTY5NjY2NTcwOS43ODIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1700"]
1340C
1340
C
ru
C. Настя и неожиданный гость
<div class="problem-statement"><div class="header"><div class="title">C. Настя и неожиданный гость</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Если девушка не идет к Денису, то Денис идет к девушке. Руководствуясь таким принципом, молодой человек вышел из дома, купил цветы и направился к Насте.</span></p><p>По пути от его дома до дома его возлюбленной есть дорога из $$$n$$$ полос, перейти которую за один зеленый свет не всегда возможно. Предвидя это, добрый мэр распорядился поставить в некоторых точках этой дороги островки безопасности. Каждый островок расположен после какой-то полосы, а также в начале и в конце дороги. На них пешеходы могут отдохнуть, набраться сил и дождаться зеленого света.</p><p>Денис подошел к левому краю дороги ровно в тот момент, когда загорелся зеленый свет. Мальчик знает, что светофор сначала горит $$$g$$$ секунд зеленым, а потом $$$r$$$ секунд красным, потом опять $$$g$$$ секунд зеленым и так далее.</p><p>Формально, дорогу можно представить как отрезок $$$[0, n]$$$. Изначально Денис стоит в точке $$$0$$$. Его задача - попасть в точку $$$n$$$ за минимальное возможное время.</p><p>Oн знает множество различных целых чисел $$$d_1, d_2, \ldots, d_m$$$, где $$$0 \leq d_i \leq n$$$  — координаты точек, в которых расположены островки безопасности. Только в одной из этих точек мальчик может находиться в момент, когда горит красный свет.</p><p>К сожалению, из-за волнения Денис не всегда может контролировать себя, поэтому сейчас на его передвижения наложены некоторые ограничения:</p><ul> <li> Он обязан двигаться всегда, пока горит зеленый, ведь сложно стоять, когда тебя ждет такая девушка. Денис за $$$1$$$ секунду может изменить свое положение на $$$\pm 1$$$. При этом он должен всегда оставаться внутри отрезка $$$[0, n]$$$. </li><li> Он может менять направление движения только на островках безопасности (ведь это безопасно). Это означает, что если за предыдущую секунду мальчик изменил свое положение на $$$+1$$$, то если он находится на островке безопасности, он может изменить свое положение на $$$\pm 1$$$, иначе он может изменить свое положение вновь только на $$$+1$$$. Аналогично, если за предыдущую секунду он изменил свое положение на $$$-1$$$, на островке безопасности он может изменить свое положение на $$$\pm 1$$$, а в любой другой точке вновь только на $$$-1$$$. </li><li> В момент, когда загорается красный, мальчик должен оказаться на каком-то островке безопасности. Он сможет продолжить движение в любом направлении, когда вновь загорится зеленый. </li></ul><p>Считается, что Денис перешел дорогу как только его координата станет равна $$$n$$$.</p><p>Эта задача оказалась не так проста, ведь возможно, таким способом даже невозможно перейти дорогу. Так как у Дениса все мысли о любви, он не справился решить ее и попросил нас помочь ему в этом. Найдите минимальное возможное время, за которое он сможет перейти дорогу по таким правилам, либо установите, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$  — ширина дороги и количество островков безопасности.</p><p>Во второй строке находится $$$m$$$ различных целых чисел $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$  — точки, в которых расположены островки безопасности. Гарантируется, что среди них есть $$$0$$$ и $$$n$$$.</p><p>В третьей строке находится два целых числа $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$  — время, которое на светофоре горит зеленый свет и время, которое на светофоре горит красный свет.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число  — минимальное время, за которое Денис может перейти дорогу по всем правилам. </p><p>Если перейти дорогу по всем правилам невозможно выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 15 5 0 3 7 14 15 11 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 45</pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 4 0 3 7 13 9 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>В первом тесте оптимальный маршрут такой: </p><ul> <li> за первый зеленый свет дойти до $$$7$$$ и вернуться на $$$3$$$. В этом случае, мы сменим направление движения в точке $$$7$$$, что разрешено, поскольку в этой точке есть островок безопасности. В конце мы окажемся в точке $$$3$$$, где также есть островок безопасности. Следующие $$$11$$$ секунд мы должны подождать красный свет. </li><li> за второй зеленый свет дойти до $$$14$$$. Снова подождать красный свет. </li><li> за $$$1$$$ секунду перейти в $$$15$$$. В итоге Денис оказывается в конце дороги. </li></ul><p>Всего получается $$$45$$$ секунд.</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="36188a36c99e435a86a71678d68b694d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f3dd79f93448a3ad2b44a4c080be0e4ea78af171"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='36188a36c99e435a86a71678d68b694d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1340%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='36188a36c99e435a86a71678d68b694d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1340">Codeforces Round 637 (Div. 1) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='36188a36c99e435a86a71678d68b694d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1340/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='36188a36c99e435a86a71678d68b694d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599367"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='36188a36c99e435a86a71678d68b694d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599367"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10795:10796" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10811" resourceName="Codeforces Round #637 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1340">Задачи</a></li> <li><a href="/contest/1340/submit">Отослать</a></li> <li><a href="/contest/1340/my">Мои посылки</a></li> <li><a href="/contest/1340/status">Статус</a></li> <li><a href="/contest/1340/hacks">Взломы</a></li> <li><a href="/contest/1340/room/1">Комната</a></li> <li><a href="/contest/1340/standings">Положение</a></li> <li><a href="/contest/1340/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b1e3749e596520f801258de54410e5f948274fc3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Настя и неожиданный гость</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Если девушка не идет к Денису, то Денис идет к девушке. Руководствуясь таким принципом, молодой человек вышел из дома, купил цветы и направился к Насте.</span></p><p>По пути от его дома до дома его возлюбленной есть дорога из $$$n$$$ полос, перейти которую за один зеленый свет не всегда возможно. Предвидя это, добрый мэр распорядился поставить в некоторых точках этой дороги островки безопасности. Каждый островок расположен после какой-то полосы, а также в начале и в конце дороги. На них пешеходы могут отдохнуть, набраться сил и дождаться зеленого света.</p><p>Денис подошел к левому краю дороги ровно в тот момент, когда загорелся зеленый свет. Мальчик знает, что светофор сначала горит $$$g$$$ секунд зеленым, а потом $$$r$$$ секунд красным, потом опять $$$g$$$ секунд зеленым и так далее.</p><p>Формально, дорогу можно представить как отрезок $$$[0, n]$$$. Изначально Денис стоит в точке $$$0$$$. Его задача - попасть в точку $$$n$$$ за минимальное возможное время.</p><p>Oн знает множество различных целых чисел $$$d_1, d_2, \ldots, d_m$$$, где $$$0 \leq d_i \leq n$$$  — координаты точек, в которых расположены островки безопасности. Только в одной из этих точек мальчик может находиться в момент, когда горит красный свет.</p><p>К сожалению, из-за волнения Денис не всегда может контролировать себя, поэтому сейчас на его передвижения наложены некоторые ограничения:</p><ul> <li> Он обязан двигаться всегда, пока горит зеленый, ведь сложно стоять, когда тебя ждет такая девушка. Денис за $$$1$$$ секунду может изменить свое положение на $$$\pm 1$$$. При этом он должен всегда оставаться внутри отрезка $$$[0, n]$$$. </li><li> Он может менять направление движения только на островках безопасности (ведь это безопасно). Это означает, что если за предыдущую секунду мальчик изменил свое положение на $$$+1$$$, то если он находится на островке безопасности, он может изменить свое положение на $$$\pm 1$$$, иначе он может изменить свое положение вновь только на $$$+1$$$. Аналогично, если за предыдущую секунду он изменил свое положение на $$$-1$$$, на островке безопасности он может изменить свое положение на $$$\pm 1$$$, а в любой другой точке вновь только на $$$-1$$$. </li><li> В момент, когда загорается красный, мальчик должен оказаться на каком-то островке безопасности. Он сможет продолжить движение в любом направлении, когда вновь загорится зеленый. </li></ul><p>Считается, что Денис перешел дорогу как только его координата станет равна $$$n$$$.</p><p>Эта задача оказалась не так проста, ведь возможно, таким способом даже невозможно перейти дорогу. Так как у Дениса все мысли о любви, он не справился решить ее и попросил нас помочь ему в этом. Найдите минимальное возможное время, за которое он сможет перейти дорогу по таким правилам, либо установите, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$  — ширина дороги и количество островков безопасности.</p><p>Во второй строке находится $$$m$$$ различных целых чисел $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$  — точки, в которых расположены островки безопасности. Гарантируется, что среди них есть $$$0$$$ и $$$n$$$.</p><p>В третьей строке находится два целых числа $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$  — время, которое на светофоре горит зеленый свет и время, которое на светофоре горит красный свет.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число  — минимальное время, за которое Денис может перейти дорогу по всем правилам. </p><p>Если перейти дорогу по всем правилам невозможно выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 15 5 0 3 7 14 15 11 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 45</pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 4 0 3 7 13 9 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>В первом тесте оптимальный маршрут такой: </p><ul> <li> за первый зеленый свет дойти до $$$7$$$ и вернуться на $$$3$$$. В этом случае, мы сменим направление движения в точке $$$7$$$, что разрешено, поскольку в этой точке есть островок безопасности. В конце мы окажемся в точке $$$3$$$, где также есть островок безопасности. Следующие $$$11$$$ секунд мы должны подождать красный свет. </li><li> за второй зеленый свет дойти до $$$14$$$. Снова подождать красный свет. </li><li> за $$$1$$$ секунду перейти в $$$15$$$. В итоге Денис оказывается в конце дороги. </li></ul><p>Всего получается $$$45$$$ секунд.</p><p>Во втором тесте невозможно перейти дорогу по всем правилам.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:51</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e55de219d34',t:'MTY5NjY2NTcxMS4zMzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2400"]
1340D
1340
D
ru
D. Настя и машина времени
<div class="problem-statement"><div class="header"><div class="title">D. Настя и машина времени</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Придя к Насте, Денис обнаружил, что она ему не рада... Но у молодого человека есть последняя надежда. Он хочет купить все вещи, что нравятся Насте. Тогда-то она уж точно согласится с ним общаться.</span></p><p>Карта города, в котором живут наши герои, представляет собой множество площадей, некоторые из которых соединены дорогами. От любой площади можно добраться до любой другой ровно одним способом, используя эти дороги и не посещая одну и ту же площадь дважды. Получается, что граф города  — это дерево.</p><p>Денис находится в вершине $$$1$$$ в момент времени $$$0$$$. Он хочет хоть раз побывать в каждой вершине и вернуться назад как можно раньше.</p><p>Денис может проходить вдоль любой дороги за $$$1$$$ времени. Увы, город столь велик, что сделать это быстро никак не выйдет. Поэтому Денис пошел на отчаянный шаг. Он достал свою карманную машину времени, которую он собрал у себя в подвале. С ее помощью Денис может стоя на месте сменить время на любое неотрицательное время, которое меньше текущего. </p><p>Но у машины времени есть один нюанс. Если герой окажется в одном месте и в одно и то же время дважды, произойдет взрыв вселенских масштабов и не получится порадовать Настю. Поэтому Денис просит вас проложить ему маршрут с использованием машины времени такой, что он обойдет все площади и вернется на первую и при этом максимальное время в котором он побывал будет минимально.</p><p>Формально, маршрут Дениса можно представить как последовательность пар $$$\{v_1, t_1\}, \{v_2, t_2\}, \{v_3, t_3\}, \ldots, \{v_k, t_k\}$$$, где $$$v_i$$$ — номер площади, а $$$t_i$$$  — время, в котором сейчас находится мальчик.</p><p>Должны быть выполнены следующие условия:</p><ul> <li> Маршрут начинается на площади $$$1$$$ в момент времени $$$0$$$, то есть $$$v_1 = 1, t_1 = 0$$$ и заканчивается на площади $$$1$$$, то есть $$$v_k = 1$$$. </li><li> Все переходы делятся на два типа: <ol> <li> Стоя на площади сменить время: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \} : v_{i+1} = v_i, 0 \leq t_{i+1} &lt; t_i$$$. </li><li> Пройти по одной из дорог: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \}$$$. При этом $$$v_i$$$ и $$$v_{i+1}$$$ соединены дорогой и $$$t_{i+1} = t_i + 1$$$. </li></ol> </li><li> Все пары $$$\{ v_i, t_i \}$$$ должны быть различны. </li><li> Среди $$$v_1, v_2, \ldots, v_k$$$ встречаются все площади. </li></ul><p>Вам нужно найти маршрут такой, что максимальное время, в котором побывает Денис будет минимальным, то есть маршрут, для которого $$$\max{(t_1, t_2, \ldots, t_k)}$$$ будет минимально возможным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — количество площадей в городе.</p><p>В следующих $$$n - 1$$$ строках находится по два целых числа $$$u$$$ и $$$v$$$ $$$(1 \leq v, u \leq n, u \neq v)$$$  — номера площадей, соединенных дорогой.</p><p>Гарантируется, что заданный граф является деревом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$k$$$ $$$(1 \leq k \leq 10^6)$$$  — длина пути Дениса.</p><p>В следующих $$$k$$$ строках выведите пары $$$v_i, t_i$$$  — пары, описывающие маршрут Дениса (как в условии).</p><p>Все требования к маршруту, описанные в условии должны быть выполнены.</p><p>Гарантируется, что при заданных ограничениях существует хотя бы один маршрут и ответ, длина которого не превосходит $$$10^6$$$. Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 2 3 2 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 13 1 0 2 1 3 2 3 1 2 2 4 3 4 1 5 2 5 1 4 2 2 3 2 0 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="b1650d2d783255d7bc61151fc9fb4b7f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f3dd79f93448a3ad2b44a4c080be0e4ea78af171"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b1650d2d783255d7bc61151fc9fb4b7f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1340%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='b1650d2d783255d7bc61151fc9fb4b7f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1340">Codeforces Round 637 (Div. 1) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='b1650d2d783255d7bc61151fc9fb4b7f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1340/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='b1650d2d783255d7bc61151fc9fb4b7f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599368"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b1650d2d783255d7bc61151fc9fb4b7f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599368"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10795:10796" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10811" resourceName="Codeforces Round #637 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1340">Задачи</a></li> <li><a href="/contest/1340/submit">Отослать</a></li> <li><a href="/contest/1340/my">Мои посылки</a></li> <li><a href="/contest/1340/status">Статус</a></li> <li><a href="/contest/1340/hacks">Взломы</a></li> <li><a href="/contest/1340/room/1">Комната</a></li> <li><a href="/contest/1340/standings">Положение</a></li> <li><a href="/contest/1340/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_98627423f718fdb93e460a19ca2381003a3d3eb5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Настя и машина времени</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Придя к Насте, Денис обнаружил, что она ему не рада... Но у молодого человека есть последняя надежда. Он хочет купить все вещи, что нравятся Насте. Тогда-то она уж точно согласится с ним общаться.</span></p><p>Карта города, в котором живут наши герои, представляет собой множество площадей, некоторые из которых соединены дорогами. От любой площади можно добраться до любой другой ровно одним способом, используя эти дороги и не посещая одну и ту же площадь дважды. Получается, что граф города  — это дерево.</p><p>Денис находится в вершине $$$1$$$ в момент времени $$$0$$$. Он хочет хоть раз побывать в каждой вершине и вернуться назад как можно раньше.</p><p>Денис может проходить вдоль любой дороги за $$$1$$$ времени. Увы, город столь велик, что сделать это быстро никак не выйдет. Поэтому Денис пошел на отчаянный шаг. Он достал свою карманную машину времени, которую он собрал у себя в подвале. С ее помощью Денис может стоя на месте сменить время на любое неотрицательное время, которое меньше текущего. </p><p>Но у машины времени есть один нюанс. Если герой окажется в одном месте и в одно и то же время дважды, произойдет взрыв вселенских масштабов и не получится порадовать Настю. Поэтому Денис просит вас проложить ему маршрут с использованием машины времени такой, что он обойдет все площади и вернется на первую и при этом максимальное время в котором он побывал будет минимально.</p><p>Формально, маршрут Дениса можно представить как последовательность пар $$$\{v_1, t_1\}, \{v_2, t_2\}, \{v_3, t_3\}, \ldots, \{v_k, t_k\}$$$, где $$$v_i$$$ — номер площади, а $$$t_i$$$  — время, в котором сейчас находится мальчик.</p><p>Должны быть выполнены следующие условия:</p><ul> <li> Маршрут начинается на площади $$$1$$$ в момент времени $$$0$$$, то есть $$$v_1 = 1, t_1 = 0$$$ и заканчивается на площади $$$1$$$, то есть $$$v_k = 1$$$. </li><li> Все переходы делятся на два типа: <ol> <li> Стоя на площади сменить время: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \} : v_{i+1} = v_i, 0 \leq t_{i+1} &lt; t_i$$$. </li><li> Пройти по одной из дорог: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \}$$$. При этом $$$v_i$$$ и $$$v_{i+1}$$$ соединены дорогой и $$$t_{i+1} = t_i + 1$$$. </li></ol> </li><li> Все пары $$$\{ v_i, t_i \}$$$ должны быть различны. </li><li> Среди $$$v_1, v_2, \ldots, v_k$$$ встречаются все площади. </li></ul><p>Вам нужно найти маршрут такой, что максимальное время, в котором побывает Денис будет минимальным, то есть маршрут, для которого $$$\max{(t_1, t_2, \ldots, t_k)}$$$ будет минимально возможным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — количество площадей в городе.</p><p>В следующих $$$n - 1$$$ строках находится по два целых числа $$$u$$$ и $$$v$$$ $$$(1 \leq v, u \leq n, u \neq v)$$$  — номера площадей, соединенных дорогой.</p><p>Гарантируется, что заданный граф является деревом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$k$$$ $$$(1 \leq k \leq 10^6)$$$  — длина пути Дениса.</p><p>В следующих $$$k$$$ строках выведите пары $$$v_i, t_i$$$  — пары, описывающие маршрут Дениса (как в условии).</p><p>Все требования к маршруту, описанные в условии должны быть выполнены.</p><p>Гарантируется, что при заданных ограничениях существует хотя бы один маршрут и ответ, длина которого не превосходит $$$10^6$$$. Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 2 3 2 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 13 1 0 2 1 3 2 3 1 2 2 4 3 4 1 5 2 5 1 4 2 2 3 2 0 1 1 </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/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:52</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e5f68c43374',t:'MTY5NjY2NTcxMi44MjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "*2600"]
1340E
1340
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-bf">К сожалению, была найдена ошибка в доказательстве авторского решения этой задачи. На данный момент нам неизвестно абсолютно верное решение. Тем не менее, вы можете сдавать эту задачу, но в случае, если ваше решение пройдет все тесты, оно не будет гарантированно верным. Если ваше решение прошло все тесты и вы уверены в доказательстве его корректности, вы можете написать одному из авторов соревнования об этом.</span></p><p><span class="tex-font-style-it"> Наверняка вы все читали книгу «Алиса в стране чудес». В этой задаче Настя оказалась в стране Трёх странных Пчёл. Пчёлы странные, потому что их соты пятиугольные. Настя пробралась туда незаконно, поэтому она хочет, чтобы вы её не поймали. Помогите пчёлам наказать нарушительницу! </span></p><p><span class="tex-font-style-bf"> Это интерактивная задача. </span></p><p>Пчелиный улей представляет собой связный неориентированный граф, по ребрам которого могут перемещаться пчелы и Настя. Граф удовлетворяет двум свойствам:</p><ul> <li> Степень любой его вершины не больше чем $$$3$$$. </li><li> Для каждого ребра существует цикл длины не больше чем $$$5$$$, проходящий через это ребро. </li></ul> <p>Есть три пчелы и Настя. Вы играете за пчел. Сначала вы выбираете вершины, в которые поставите пчел. Затем Настя выбирает вершину, в которой она изначально окажется. Один ход представляет из себя перемещения сначала пчел, потом Насти, по очереди: </p><ol> <li> Для каждой из ваших пчел, вы можете либо переместить каждую ее по какому-нибудь ребру графа, выходящему из вершины, где находится эта пчела или оставить ее на месте. </li><li> Затем Настя <span class="tex-font-style-bf">обязательно</span> перемещается по какому-нибудь ребру графа, выходящему из вершины, в которой она сейчас находится. </li></ol><p>Вы побеждаете, если хотя бы одна из пчел и Настя оказываются в одной вершине в любой момент игры.</p><p>Если после $$$n$$$ ходов такая ситуация не происходит, то вы проигрываете.</p><p><span class="tex-font-style-bf">Несколько пчел могут находиться в одной и той же вершине.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два целых числа $$$n$$$ $$$(4 \leq n \leq 5000)$$$ и $$$m$$$ $$$(n \leq m \leq 3n)$$$  — количество вершин и рёбер в графе.</p><p>Каждая из следующих $$$m$$$ строк содержит по два целых числа $$$v$$$ и $$$u$$$ $$$(1 \leq v, u \leq n)$$$, которые означают, что между вершинами $$$v$$$ и $$$u$$$ есть ребро. Гарантируется, что граф связен, не содержит петель, что степень любой вершины не превосходит $$$3$$$ и через каждое ребро проходит цикл длины не больше чем $$$5$$$. Обратите внимание, граф <span class="tex-font-style-bf">может</span> содержать кратные рёбра.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>На каждом ходу вы должны выводить ровно по три вершины $$$a, b, c$$$ $$$(1 \leq a, b, c \leq n)$$$. В первый раз выведенные $$$3$$$ вершины будут означать, в какие вершины вы изначально поставили пчел. В ответ вы получите вершину, в которую жюри расположило Настю. Каждые следующие $$$3$$$ вершины будут означать, где оказываются $$$3$$$ пчелы после вашего хода. Каждая из пчел может независимо от других пчел как остаться в текущей вершине, так и переместиться по ребру. После очередного вывода $$$3$$$ вершин, в ответ вы получаете номер новой вершины, в которую пошла Настя.</p><p>Как только одна из пчёл оказалась в одной вершине с Настей или вы достигли лимита на количество ходов, ваша программа должна завершить работу. То есть, если вы сделали ход, и одна из пчел оказалась в одной вершине с Настей, ваша программа должна завершить работу, либо если Настя сделала ход и оказалась в одной вершине с одной из пчел, вы не должны делать свой ход и программа должна завершить работу.</p><p>При превышении лимита на количество ходов (то есть количество ваших ходов превысило $$$n$$$, где $$$n$$$  — количество вершин в графе) будет ваша программа получит вердикт неправильный ответ, в случае немедленного завершения.</p><p>Ваше решение может получить вердикт <span class="tex-font-style-it">Решение «зависло»</span>, если вы ничего не выведете или забудете сбросить буфер вывода.</p><p>Чтобы сбросить буфер вывода вам нужно сделать следующее сразу после вывода запроса и символа конца строки:</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>В этой задаче интерактор адаптивный. Это означает, что в зависимости от всех ваших предыдущих ходов поведение Насти может изменяться. </p><p><span class="tex-font-style-bf">Взломы</span> недоступны для этой задачи.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 2 2 3 3 4 4 5 5 1 4 5</pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 1 5 3</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 9 1 2 2 3 3 4 4 5 5 1 5 6 6 7 7 8 8 4 1 5</pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 3 3 6 2 2 5 3 1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пусть Настя - это зелёная фишка, а три пронумерованных красных - это три пчелы.</p><p>В первом тесте перемещение героев выглядит так.</p><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/c272d9bbf84f7af62b88946b85e60969ac5d84bd.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> <span class="tex-font-size-small">После выбора стартовых вершин.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/602ed1429a012600b037447f89797ed7ccc4ca52.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> <span class="tex-font-size-small">Первых ход после перемещения пчёл.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/399639c28c29178e8f3d5f023ba30360b8609f64.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> <span class="tex-font-size-small">Первых ход после перемещения Насти. Настя поймана пчелой 1.</span> </center><p>Во втором тесте перемещение героев выглядит так.</p><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/e43d3c0e18e637ca84771ad4811899ba911880d2.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> <span class="tex-font-size-small">После выбора стартовых вершин.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/255504d0e8872e4df03360a993ca349cd9741db4.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> <span class="tex-font-size-small">Первых ход после перемещения пчёл.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/7f663d0e3901604481c18a3e97e6861480c1468c.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> <span class="tex-font-size-small">Первых ход после перемещения Насти.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/af912445c35da0b5852dbe46dd84137c5267aa14.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> <span class="tex-font-size-small">Второй ход после перемещения пчёл. Настя поймана пчелой 1.</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="735c6064415b1739c88283a822e54d5c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f3dd79f93448a3ad2b44a4c080be0e4ea78af171"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='735c6064415b1739c88283a822e54d5c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1340%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='735c6064415b1739c88283a822e54d5c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1340">Codeforces Round 637 (Div. 1) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='735c6064415b1739c88283a822e54d5c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1340/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound 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='735c6064415b1739c88283a822e54d5c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599369"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='735c6064415b1739c88283a822e54d5c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599369"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10795:10796" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10811" resourceName="Codeforces Round #637 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1340">Задачи</a></li> <li><a href="/contest/1340/submit">Отослать</a></li> <li><a href="/contest/1340/my">Мои посылки</a></li> <li><a href="/contest/1340/status">Статус</a></li> <li><a href="/contest/1340/hacks">Взломы</a></li> <li><a href="/contest/1340/room/1">Комната</a></li> <li><a href="/contest/1340/standings">Положение</a></li> <li><a href="/contest/1340/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2738c657d0dd18e0c726deb802e502281da62910"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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-bf">К сожалению, была найдена ошибка в доказательстве авторского решения этой задачи. На данный момент нам неизвестно абсолютно верное решение. Тем не менее, вы можете сдавать эту задачу, но в случае, если ваше решение пройдет все тесты, оно не будет гарантированно верным. Если ваше решение прошло все тесты и вы уверены в доказательстве его корректности, вы можете написать одному из авторов соревнования об этом.</span></p><p><span class="tex-font-style-it"> Наверняка вы все читали книгу «Алиса в стране чудес». В этой задаче Настя оказалась в стране Трёх странных Пчёл. Пчёлы странные, потому что их соты пятиугольные. Настя пробралась туда незаконно, поэтому она хочет, чтобы вы её не поймали. Помогите пчёлам наказать нарушительницу! </span></p><p><span class="tex-font-style-bf"> Это интерактивная задача. </span></p><p>Пчелиный улей представляет собой связный неориентированный граф, по ребрам которого могут перемещаться пчелы и Настя. Граф удовлетворяет двум свойствам:</p><ul> <li> Степень любой его вершины не больше чем $$$3$$$. </li><li> Для каждого ребра существует цикл длины не больше чем $$$5$$$, проходящий через это ребро. </li></ul> <p>Есть три пчелы и Настя. Вы играете за пчел. Сначала вы выбираете вершины, в которые поставите пчел. Затем Настя выбирает вершину, в которой она изначально окажется. Один ход представляет из себя перемещения сначала пчел, потом Насти, по очереди: </p><ol> <li> Для каждой из ваших пчел, вы можете либо переместить каждую ее по какому-нибудь ребру графа, выходящему из вершины, где находится эта пчела или оставить ее на месте. </li><li> Затем Настя <span class="tex-font-style-bf">обязательно</span> перемещается по какому-нибудь ребру графа, выходящему из вершины, в которой она сейчас находится. </li></ol><p>Вы побеждаете, если хотя бы одна из пчел и Настя оказываются в одной вершине в любой момент игры.</p><p>Если после $$$n$$$ ходов такая ситуация не происходит, то вы проигрываете.</p><p><span class="tex-font-style-bf">Несколько пчел могут находиться в одной и той же вершине.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два целых числа $$$n$$$ $$$(4 \leq n \leq 5000)$$$ и $$$m$$$ $$$(n \leq m \leq 3n)$$$  — количество вершин и рёбер в графе.</p><p>Каждая из следующих $$$m$$$ строк содержит по два целых числа $$$v$$$ и $$$u$$$ $$$(1 \leq v, u \leq n)$$$, которые означают, что между вершинами $$$v$$$ и $$$u$$$ есть ребро. Гарантируется, что граф связен, не содержит петель, что степень любой вершины не превосходит $$$3$$$ и через каждое ребро проходит цикл длины не больше чем $$$5$$$. Обратите внимание, граф <span class="tex-font-style-bf">может</span> содержать кратные рёбра.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>На каждом ходу вы должны выводить ровно по три вершины $$$a, b, c$$$ $$$(1 \leq a, b, c \leq n)$$$. В первый раз выведенные $$$3$$$ вершины будут означать, в какие вершины вы изначально поставили пчел. В ответ вы получите вершину, в которую жюри расположило Настю. Каждые следующие $$$3$$$ вершины будут означать, где оказываются $$$3$$$ пчелы после вашего хода. Каждая из пчел может независимо от других пчел как остаться в текущей вершине, так и переместиться по ребру. После очередного вывода $$$3$$$ вершин, в ответ вы получаете номер новой вершины, в которую пошла Настя.</p><p>Как только одна из пчёл оказалась в одной вершине с Настей или вы достигли лимита на количество ходов, ваша программа должна завершить работу. То есть, если вы сделали ход, и одна из пчел оказалась в одной вершине с Настей, ваша программа должна завершить работу, либо если Настя сделала ход и оказалась в одной вершине с одной из пчел, вы не должны делать свой ход и программа должна завершить работу.</p><p>При превышении лимита на количество ходов (то есть количество ваших ходов превысило $$$n$$$, где $$$n$$$  — количество вершин в графе) будет ваша программа получит вердикт неправильный ответ, в случае немедленного завершения.</p><p>Ваше решение может получить вердикт <span class="tex-font-style-it">Решение «зависло»</span>, если вы ничего не выведете или забудете сбросить буфер вывода.</p><p>Чтобы сбросить буфер вывода вам нужно сделать следующее сразу после вывода запроса и символа конца строки:</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>В этой задаче интерактор адаптивный. Это означает, что в зависимости от всех ваших предыдущих ходов поведение Насти может изменяться. </p><p><span class="tex-font-style-bf">Взломы</span> недоступны для этой задачи.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 2 2 3 3 4 4 5 5 1 4 5</pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 1 5 3</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 9 1 2 2 3 3 4 4 5 5 1 5 6 6 7 7 8 8 4 1 5</pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 3 3 6 2 2 5 3 1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пусть Настя - это зелёная фишка, а три пронумерованных красных - это три пчелы.</p><p>В первом тесте перемещение героев выглядит так.</p><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/c272d9bbf84f7af62b88946b85e60969ac5d84bd.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> <span class="tex-font-size-small">После выбора стартовых вершин.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/602ed1429a012600b037447f89797ed7ccc4ca52.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> <span class="tex-font-size-small">Первых ход после перемещения пчёл.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/399639c28c29178e8f3d5f023ba30360b8609f64.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> <span class="tex-font-size-small">Первых ход после перемещения Насти. Настя поймана пчелой 1.</span> </center><p>Во втором тесте перемещение героев выглядит так.</p><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/e43d3c0e18e637ca84771ad4811899ba911880d2.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> <span class="tex-font-size-small">После выбора стартовых вершин.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/255504d0e8872e4df03360a993ca349cd9741db4.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> <span class="tex-font-size-small">Первых ход после перемещения пчёл.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/7f663d0e3901604481c18a3e97e6861480c1468c.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> <span class="tex-font-size-small">Первых ход после перемещения Насти.</span> </center><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/af912445c35da0b5852dbe46dd84137c5267aa14.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> <span class="tex-font-size-small">Второй ход после перемещения пчёл. Настя поймана пчелой 1.</span> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:54</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e68efbd9d76',t:'MTY5NjY2NTcxNC4yNjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0412\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438, \u043c\u0430\u0442. \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f, \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3000"]
1340F
1340
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> <span class="tex-font-style-it"> Настя, как и вы  — олимпиадный программист, но она только учится. Недавно Денис ей рассказал о способе проверки строки на то, что она является правильной скобочной последовательностью. После этого неожиданно Настя придумала более сложную задачу, которую Денис не смог решить, а сможете ли Вы? </span></p><p>Дана строка $$$s$$$, состоящая из $$$k$$$ видов пар скобок. Каждая скобка имеет вид $$$t$$$ — целое число, такое что $$$1 \leq |t| \leq k$$$. Если скобка имеет вид $$$t$$$, то:</p><ul> <li> Если $$$t &gt; 0$$$, то это открывающая скобка типа $$$t$$$. </li><li> Если $$$t &lt; 0$$$, то это закрывающая скобка типа $$$-t$$$. </li></ul><p>Таким образом, всего существует $$$k$$$ типов пар скобок.</p><p>Требуется отвечать на следующие запросы: </p><ol> <li> Заменить скобку на позиции $$$i$$$ на скобку вида $$$t$$$. </li><li> Проверить, является ли подстрока с $$$l$$$-й по $$$r$$$-ю позиции, включительно, правильной скобочной последовательностью. </li></ol><p>Напомним определение правильной скобочной последовательности:</p><ul> <li> Пустая последовательность является правильной. </li><li> Если $$$A$$$ и $$$B$$$ - две правильные скобочные последовательности, то их конкатенация «$$$A$$$ $$$B$$$» тоже является правильной скобочной последовательностью. </li><li> Если $$$A$$$ - правильная скобочная последовательность, $$$c$$$ $$$(1 \leq c \leq k)$$$  — некоторый тип скобок, то последовательность «$$$c$$$ $$$A$$$ $$$-c$$$» тоже является правильной. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — длина строки и число $$$k$$$ $$$(1 \leq k \leq n)$$$  — количество типов скобок.</p><p>Во второй строке дана строка $$$s$$$ длиной $$$n$$$ символов  — $$$n$$$ целых чисел $$$s_1, s_2, \ldots, s_n$$$ $$$(1 \leq |s_i| \leq k)$$$.</p><p>В третьей строке дано число $$$q$$$ $$$(1 \leq q \leq 10^5)$$$  — количество запросов.</p><p>Каждая из следующих $$$q$$$ строк описывает запросы: </p><ul> <li> $$$1$$$ $$$i$$$ $$$t$$$ - запрос $$$1$$$-го типа $$$(1 \leq i \leq n, 1 \leq |t| \leq k)$$$. </li><li> $$$2$$$ $$$l$$$ $$$r$$$ - запрос $$$2$$$-го типа $$$(1 \leq l \leq r \leq n)$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса $$$2$$$ типа выведите «<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 1 -1 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 -2 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 2 -2 -1 1 -1 3 2 1 6 2 1 4 2 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes No </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 -1 1 4 2 1 2 1 1 1 1 2 -1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В четвёртом тесте изначально строка не является правильной скобочной последовательностью, значит ответ на первый вопрос «<span class="tex-font-style-tt">No</span>». После двух изменений она имеет вид «<span class="tex-font-style-tt">$$$1$$$ $$$-1$$$</span>», значит она стала правильной скобочной последовательностью и ответ на четвёртый запрос «<span class="tex-font-style-tt">Yes</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="b107ffac61a27b2cd29fcef9b2e8ae09"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="k3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/34424/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="f3dd79f93448a3ad2b44a4c080be0e4ea78af171"/> <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/34424/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/34424/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/34424/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/34424/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/34424/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/34424/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/34424/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/34424/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/34424/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/34424/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/34424/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/34424/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/34424/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/34424/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/34424/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/34424/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d77efe4c9b2300bb32967c24ca77b18b/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/34424/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/34424/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/34424/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b107ffac61a27b2cd29fcef9b2e8ae09'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/34424/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/34424/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/34424/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1340%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='b107ffac61a27b2cd29fcef9b2e8ae09'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1340">Codeforces Round 637 (Div. 1) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='b107ffac61a27b2cd29fcef9b2e8ae09'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1340/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound 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='b107ffac61a27b2cd29fcef9b2e8ae09'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599376"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b107ffac61a27b2cd29fcef9b2e8ae09'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599376"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10795:10796" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10811" resourceName="Codeforces Round #637 Editorial" resourceManual="true" src="//codeforces.org/s/34424/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1340">Задачи</a></li> <li><a href="/contest/1340/submit">Отослать</a></li> <li><a href="/contest/1340/my">Мои посылки</a></li> <li><a href="/contest/1340/status">Статус</a></li> <li><a href="/contest/1340/hacks">Взломы</a></li> <li><a href="/contest/1340/room/1">Комната</a></li> <li><a href="/contest/1340/standings">Положение</a></li> <li><a href="/contest/1340/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8f6c8f88754b587659813f4e766548636928d6d8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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> <span class="tex-font-style-it"> Настя, как и вы  — олимпиадный программист, но она только учится. Недавно Денис ей рассказал о способе проверки строки на то, что она является правильной скобочной последовательностью. После этого неожиданно Настя придумала более сложную задачу, которую Денис не смог решить, а сможете ли Вы? </span></p><p>Дана строка $$$s$$$, состоящая из $$$k$$$ видов пар скобок. Каждая скобка имеет вид $$$t$$$ — целое число, такое что $$$1 \leq |t| \leq k$$$. Если скобка имеет вид $$$t$$$, то:</p><ul> <li> Если $$$t &gt; 0$$$, то это открывающая скобка типа $$$t$$$. </li><li> Если $$$t &lt; 0$$$, то это закрывающая скобка типа $$$-t$$$. </li></ul><p>Таким образом, всего существует $$$k$$$ типов пар скобок.</p><p>Требуется отвечать на следующие запросы: </p><ol> <li> Заменить скобку на позиции $$$i$$$ на скобку вида $$$t$$$. </li><li> Проверить, является ли подстрока с $$$l$$$-й по $$$r$$$-ю позиции, включительно, правильной скобочной последовательностью. </li></ol><p>Напомним определение правильной скобочной последовательности:</p><ul> <li> Пустая последовательность является правильной. </li><li> Если $$$A$$$ и $$$B$$$ - две правильные скобочные последовательности, то их конкатенация «$$$A$$$ $$$B$$$» тоже является правильной скобочной последовательностью. </li><li> Если $$$A$$$ - правильная скобочная последовательность, $$$c$$$ $$$(1 \leq c \leq k)$$$  — некоторый тип скобок, то последовательность «$$$c$$$ $$$A$$$ $$$-c$$$» тоже является правильной. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — длина строки и число $$$k$$$ $$$(1 \leq k \leq n)$$$  — количество типов скобок.</p><p>Во второй строке дана строка $$$s$$$ длиной $$$n$$$ символов  — $$$n$$$ целых чисел $$$s_1, s_2, \ldots, s_n$$$ $$$(1 \leq |s_i| \leq k)$$$.</p><p>В третьей строке дано число $$$q$$$ $$$(1 \leq q \leq 10^5)$$$  — количество запросов.</p><p>Каждая из следующих $$$q$$$ строк описывает запросы: </p><ul> <li> $$$1$$$ $$$i$$$ $$$t$$$ - запрос $$$1$$$-го типа $$$(1 \leq i \leq n, 1 \leq |t| \leq k)$$$. </li><li> $$$2$$$ $$$l$$$ $$$r$$$ - запрос $$$2$$$-го типа $$$(1 \leq l \leq r \leq n)$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса $$$2$$$ типа выведите «<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 1 -1 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 -2 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 2 -2 -1 1 -1 3 2 1 6 2 1 4 2 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes No </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 -1 1 4 2 1 2 1 1 1 1 2 -1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В четвёртом тесте изначально строка не является правильной скобочной последовательностью, значит ответ на первый вопрос «<span class="tex-font-style-tt">No</span>». После двух изменений она имеет вид «<span class="tex-font-style-tt">$$$1$$$ $$$-1$$$</span>», значит она стала правильной скобочной последовательностью и ответ на четвёртый запрос «<span class="tex-font-style-tt">Yes</span>».</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/34424"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01:55</span> (k3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/34424/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/34424/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/34424/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/34424/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-34424.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81249e71be4f3a71',t:'MTY5NjY2NTcxNS42MjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0445\u044d\u0448\u0438", "*3300"]
1341A
1341
A
ru
A. Настя и рис
<div class="problem-statement"><div class="header"><div class="title">A. Настя и рис</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Только что Настя совершила огромную ошибку и рассыпала целую упаковку риса на пол. Скоро придёт мама. Если она это увидит, то Настю накажут и поставят в угол.</p><p>Всего Настя просыпала $$$n$$$ зёрен. Настя прочла, что каждое зерно весит некоторое целое число грамм от $$$a - b$$$ до $$$a + b$$$ грамм включительно (числа $$$a$$$ и $$$b$$$ известны), а вся упаковка из $$$n$$$ зёрен весит от $$$c - d$$$ до $$$c + d$$$ грамм, включительно (числа $$$c$$$ и $$$d$$$ известны). Вес упаковки  — это сумма весов всех $$$n$$$ зёрен в ней.</p><p>Помогите понять Насте, может ли прочитанная информация быть верной. Иными словами, проверьте, может ли у каждого зерна быть такая масса, что $$$i$$$-е зерно весит некоторое целое число грамм $$$x_i$$$ $$$(a - b \leq x_i \leq a + b)$$$, а в сумме они весят от $$$c - d$$$ до $$$c + d$$$, включительно (то есть $$$c - d \leq \sum\limits_{i=1}^{n}{x_i} \leq c + d$$$).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат несколько наборов входных данных. В первой строке задано единственное число $$$t$$$ $$$(1 \leq t \leq 1000)$$$ — количество наборов входных данных. </p><p>Следующие $$$t$$$ строк содержат описания наборов входных данных, каждая строка содержит по $$$5$$$ целых чисел: $$$n$$$ $$$(1 \leq n \leq 1000)$$$  — количество зерен, которое насчитала Настя и $$$a, b, c, d$$$ $$$(0 \leq b &lt; a \leq 1000, 0 \leq d &lt; c \leq 1000)$$$  — числа, определяющие возможный вес одного зерна риса (от $$$a - b$$$ до $$$a + b$$$) и возможный суммарный вес упаковки (от $$$c - d$$$ до $$$c + d$$$).</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>», если $$$n$$$ зёрен массами от $$$a - b$$$ до $$$a + b$$$ не могут составить упаковку суммарной массой от $$$c - d$$$ до $$$c + d$$$.</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 7 20 3 101 18 11 11 10 234 2 8 9 7 250 122 19 41 21 321 10 3 10 8 6 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте можно предположить, что каждое зерно весит по $$$17$$$ грамм, а пачка $$$119$$$ грамм, тогда действительно Настя могла собрать всю пачку.</p><p>Во третьем тесте можно предположить, что каждое зерно весит по $$$16$$$ грамм, а пачка $$$128$$$ грамм, тогда действительно Настя могла собрать всю пачку.</p><p>Во пятом тесте можно предположить, что $$$3$$$ зерна риса весят $$$2$$$, $$$2$$$ и $$$3$$$ грамма, а пачка $$$7$$$ грамм, тогда действительно Настя могла собрать всю пачку.</p><p>Во втором и в четвёртом тестах можно доказать, что нельзя определить корректные веса всех зёрен риса и вес пачки так, чтобы вес пачки оказался равен суммарному весу всех собранных зерен.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="ced5c9476b29365af54e467ca928f78b"/> <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="e4f8638a89cd11d45a9a414a818e6025d7999ac3"/> <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='ced5c9476b29365af54e467ca928f78b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1341%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='ced5c9476b29365af54e467ca928f78b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1341">Codeforces Round 637 (Div. 2) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='ced5c9476b29365af54e467ca928f78b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1341/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='ced5c9476b29365af54e467ca928f78b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599358"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ced5c9476b29365af54e467ca928f78b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599358"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10797:10798" 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/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10812" resourceName="Codeforces Round #637 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/1341">Задачи</a></li> <li><a href="/contest/1341/submit">Отослать</a></li> <li><a href="/contest/1341/my">Мои посылки</a></li> <li><a href="/contest/1341/status">Статус</a></li> <li><a href="/contest/1341/hacks">Взломы</a></li> <li><a href="/contest/1341/room/1">Комната</a></li> <li><a href="/contest/1341/standings">Положение</a></li> <li><a href="/contest/1341/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_fc58e181db668b067613796e20e769f9e24c6b76"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Настя и рис</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Только что Настя совершила огромную ошибку и рассыпала целую упаковку риса на пол. Скоро придёт мама. Если она это увидит, то Настю накажут и поставят в угол.</p><p>Всего Настя просыпала $$$n$$$ зёрен. Настя прочла, что каждое зерно весит некоторое целое число грамм от $$$a - b$$$ до $$$a + b$$$ грамм включительно (числа $$$a$$$ и $$$b$$$ известны), а вся упаковка из $$$n$$$ зёрен весит от $$$c - d$$$ до $$$c + d$$$ грамм, включительно (числа $$$c$$$ и $$$d$$$ известны). Вес упаковки  — это сумма весов всех $$$n$$$ зёрен в ней.</p><p>Помогите понять Насте, может ли прочитанная информация быть верной. Иными словами, проверьте, может ли у каждого зерна быть такая масса, что $$$i$$$-е зерно весит некоторое целое число грамм $$$x_i$$$ $$$(a - b \leq x_i \leq a + b)$$$, а в сумме они весят от $$$c - d$$$ до $$$c + d$$$, включительно (то есть $$$c - d \leq \sum\limits_{i=1}^{n}{x_i} \leq c + d$$$).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат несколько наборов входных данных. В первой строке задано единственное число $$$t$$$ $$$(1 \leq t \leq 1000)$$$ — количество наборов входных данных. </p><p>Следующие $$$t$$$ строк содержат описания наборов входных данных, каждая строка содержит по $$$5$$$ целых чисел: $$$n$$$ $$$(1 \leq n \leq 1000)$$$  — количество зерен, которое насчитала Настя и $$$a, b, c, d$$$ $$$(0 \leq b &lt; a \leq 1000, 0 \leq d &lt; c \leq 1000)$$$  — числа, определяющие возможный вес одного зерна риса (от $$$a - b$$$ до $$$a + b$$$) и возможный суммарный вес упаковки (от $$$c - d$$$ до $$$c + d$$$).</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>», если $$$n$$$ зёрен массами от $$$a - b$$$ до $$$a + b$$$ не могут составить упаковку суммарной массой от $$$c - d$$$ до $$$c + d$$$.</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 7 20 3 101 18 11 11 10 234 2 8 9 7 250 122 19 41 21 321 10 3 10 8 6 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте можно предположить, что каждое зерно весит по $$$17$$$ грамм, а пачка $$$119$$$ грамм, тогда действительно Настя могла собрать всю пачку.</p><p>Во третьем тесте можно предположить, что каждое зерно весит по $$$16$$$ грамм, а пачка $$$128$$$ грамм, тогда действительно Настя могла собрать всю пачку.</p><p>Во пятом тесте можно предположить, что $$$3$$$ зерна риса весят $$$2$$$, $$$2$$$ и $$$3$$$ грамма, а пачка $$$7$$$ грамм, тогда действительно Настя могла собрать всю пачку.</p><p>Во втором и в четвёртом тестах можно доказать, что нельзя определить корректные веса всех зёрен риса и вес пачки так, чтобы вес пачки оказался равен суммарному весу всех собранных зерен.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:01: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:'81249e7a5f7c9d4f',t:'MTY5NjY2NTcxNy4wOTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1341B
1341
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>На 14 февраля Денис решил подарить валентинку Насте и не придумал ничего лучше чем нарисовать на двери длины $$$k$$$ ($$$k \ge 3$$$) огромное красное сердечко. Настю такой подарок очень смутил, поэтому она решила сломать дверь, сбросив её на горы.</p><p>Горы описываются последовательностью высот $$$a_1, a_2, \dots, a_n$$$ в порядке слева направо ($$$k \le n$$$). Гарантируется, что соседние высоты не равны друг другу (то есть $$$a_i \ne a_{i+1}$$$ для всех $$$i$$$ от $$$1$$$ до $$$n-1$$$).</p><p>Пиками гор на отрезке $$$[l,r]$$$ (от $$$l$$$ до $$$r$$$) называются такие индексы $$$i$$$, что $$$l &lt; i &lt; r$$$, $$$a_{i - 1} &lt; a_i$$$ и $$$a_i &gt; a_{i + 1}$$$. Стоит отметить, что граничные для отрезка индексы $$$l$$$ и $$$r$$$ пиками <span class="tex-font-style-bf">не являются</span>. Например, если $$$n=8$$$ и $$$a=[3,1,4,1,5,9,2,6]$$$, то на отрезке $$$[1,8]$$$ всего два пика (с индексами $$$3$$$ и $$$6$$$), а на отрезке $$$[3, 6]$$$ — пиков нет.</p><p>Чтобы сломать дверь, Настя сбрасывает ее на некоторый отрезок $$$[l,l+k-1]$$$ подряд идущих гор длины $$$k$$$ ($$$1 \le l \le n-k+1$$$). Когда дверь касается пиков гор, она разламывается на две части, после этого эти части продолжат падать в разных половинах и также ломаться на части при касании пиков гор и так далее. Формально, количество частей, на которое разобьется дверь, будет равно $$$p+1$$$, где $$$p$$$ — количество пиков на отрезке $$$[l,l+k-1]$$$.</p><p>Настя хочет сломать ее на максимальное количество кусочков. Помогите ей выбрать такой отрезок гор $$$[l, l+k-1]$$$, что количество пиков на нём — максимально. Если существует несколько оптимальных отрезков, Настя желает найти такой, для которого значение $$$l$$$ — минимально.</p><p>Формально, то вам нужно выбрать такой отрезок гор $$$[l, l+k-1]$$$, на котором количество пиков максимально. Среди всех таких отрезков, вам нужно найти отрезок, имеющий минимальное значение $$$l$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных в тесте. Далее содержатся сами описания наборов.</p><p>В первой строке набора находятся два целых числа $$$n$$$ и $$$k$$$ ($$$3 \leq k \leq n \leq 2 \cdot 10^5$$$)  — количество гор и длина Настиной двери.</p><p>Вторая строка набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 10 ^ 9$$$, $$$a_i \neq a_{i + 1}$$$), задающие высоты гор.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите два целых числа $$$t$$$ и $$$l$$$  — максимальное количество частей, на которое может разбиться дверь, и левую границу отрезка длины $$$k$$$, на который надо сбросить дверь.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 8 6 1 2 4 1 2 4 1 2 5 3 3 2 3 2 1 10 4 4 3 4 3 2 3 2 1 0 1 15 7 3 7 4 8 2 3 4 5 21 2 3 4 2 1 3 7 5 1 2 3 4 5 6 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 2 2 2 1 3 1 2 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нужно выбрать отрезок гор со $$$2$$$ по $$$7$$$, на этом отрезке индексы $$$3$$$ и $$$6$$$ являются пиками, поэтому ответ равен $$$3$$$ (всего $$$2$$$ пика, значит дверь разломится на $$$3$$$ части). Не трудно заметить, что отрезки гор $$$[1, 6]$$$ и $$$[3, 8]$$$ не подойдут, так как на них всего $$$1$$$ пик (для первого отрезка индекс $$$6$$$ не является пиком, а для второго отрезка индекс $$$3$$$ не является пиком). </p><p>Во втором примере нужно выбрать отрезок гор со $$$2$$$ по $$$4$$$, на этом отрезке индекс $$$3$$$ является пиком, поэтому ответ равен $$$2$$$ (всего $$$1$$$ пик, значит дверь разломится на $$$2$$$ части).</p><p>В третьем примере нужно выбрать отрезок гор с $$$1$$$ по $$$4$$$, на этом отрезке индекс $$$3$$$ является пиком, поэтому ответ равен $$$2$$$ (всего $$$1$$$ пик, значит дверь разломится на $$$2$$$ части). Можно заметить, что на отрезках $$$[2, 5]$$$, $$$[4, 7]$$$ и $$$[5, 8]$$$ количество пиков также равно $$$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="1c86c6310a8e16bd43be5f0cf9a9d7d8"/> <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="e4f8638a89cd11d45a9a414a818e6025d7999ac3"/> <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='1c86c6310a8e16bd43be5f0cf9a9d7d8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1341%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='1c86c6310a8e16bd43be5f0cf9a9d7d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1341">Codeforces Round 637 (Div. 2) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='1c86c6310a8e16bd43be5f0cf9a9d7d8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1341/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='1c86c6310a8e16bd43be5f0cf9a9d7d8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599359"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1c86c6310a8e16bd43be5f0cf9a9d7d8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599359"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10797:10798" 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/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10812" resourceName="Codeforces Round #637 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/1341">Задачи</a></li> <li><a href="/contest/1341/submit">Отослать</a></li> <li><a href="/contest/1341/my">Мои посылки</a></li> <li><a href="/contest/1341/status">Статус</a></li> <li><a href="/contest/1341/hacks">Взломы</a></li> <li><a href="/contest/1341/room/1">Комната</a></li> <li><a href="/contest/1341/standings">Положение</a></li> <li><a href="/contest/1341/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_11bdf64f73cca552b4ea4be216225acbddf7c01a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>На 14 февраля Денис решил подарить валентинку Насте и не придумал ничего лучше чем нарисовать на двери длины $$$k$$$ ($$$k \ge 3$$$) огромное красное сердечко. Настю такой подарок очень смутил, поэтому она решила сломать дверь, сбросив её на горы.</p><p>Горы описываются последовательностью высот $$$a_1, a_2, \dots, a_n$$$ в порядке слева направо ($$$k \le n$$$). Гарантируется, что соседние высоты не равны друг другу (то есть $$$a_i \ne a_{i+1}$$$ для всех $$$i$$$ от $$$1$$$ до $$$n-1$$$).</p><p>Пиками гор на отрезке $$$[l,r]$$$ (от $$$l$$$ до $$$r$$$) называются такие индексы $$$i$$$, что $$$l &lt; i &lt; r$$$, $$$a_{i - 1} &lt; a_i$$$ и $$$a_i &gt; a_{i + 1}$$$. Стоит отметить, что граничные для отрезка индексы $$$l$$$ и $$$r$$$ пиками <span class="tex-font-style-bf">не являются</span>. Например, если $$$n=8$$$ и $$$a=[3,1,4,1,5,9,2,6]$$$, то на отрезке $$$[1,8]$$$ всего два пика (с индексами $$$3$$$ и $$$6$$$), а на отрезке $$$[3, 6]$$$ — пиков нет.</p><p>Чтобы сломать дверь, Настя сбрасывает ее на некоторый отрезок $$$[l,l+k-1]$$$ подряд идущих гор длины $$$k$$$ ($$$1 \le l \le n-k+1$$$). Когда дверь касается пиков гор, она разламывается на две части, после этого эти части продолжат падать в разных половинах и также ломаться на части при касании пиков гор и так далее. Формально, количество частей, на которое разобьется дверь, будет равно $$$p+1$$$, где $$$p$$$ — количество пиков на отрезке $$$[l,l+k-1]$$$.</p><p>Настя хочет сломать ее на максимальное количество кусочков. Помогите ей выбрать такой отрезок гор $$$[l, l+k-1]$$$, что количество пиков на нём — максимально. Если существует несколько оптимальных отрезков, Настя желает найти такой, для которого значение $$$l$$$ — минимально.</p><p>Формально, то вам нужно выбрать такой отрезок гор $$$[l, l+k-1]$$$, на котором количество пиков максимально. Среди всех таких отрезков, вам нужно найти отрезок, имеющий минимальное значение $$$l$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных в тесте. Далее содержатся сами описания наборов.</p><p>В первой строке набора находятся два целых числа $$$n$$$ и $$$k$$$ ($$$3 \leq k \leq n \leq 2 \cdot 10^5$$$)  — количество гор и длина Настиной двери.</p><p>Вторая строка набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 10 ^ 9$$$, $$$a_i \neq a_{i + 1}$$$), задающие высоты гор.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите два целых числа $$$t$$$ и $$$l$$$  — максимальное количество частей, на которое может разбиться дверь, и левую границу отрезка длины $$$k$$$, на который надо сбросить дверь.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 8 6 1 2 4 1 2 4 1 2 5 3 3 2 3 2 1 10 4 4 3 4 3 2 3 2 1 0 1 15 7 3 7 4 8 2 3 4 5 21 2 3 4 2 1 3 7 5 1 2 3 4 5 6 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 2 2 2 1 3 1 2 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нужно выбрать отрезок гор со $$$2$$$ по $$$7$$$, на этом отрезке индексы $$$3$$$ и $$$6$$$ являются пиками, поэтому ответ равен $$$3$$$ (всего $$$2$$$ пика, значит дверь разломится на $$$3$$$ части). Не трудно заметить, что отрезки гор $$$[1, 6]$$$ и $$$[3, 8]$$$ не подойдут, так как на них всего $$$1$$$ пик (для первого отрезка индекс $$$6$$$ не является пиком, а для второго отрезка индекс $$$3$$$ не является пиком). </p><p>Во втором примере нужно выбрать отрезок гор со $$$2$$$ по $$$4$$$, на этом отрезке индекс $$$3$$$ является пиком, поэтому ответ равен $$$2$$$ (всего $$$1$$$ пик, значит дверь разломится на $$$2$$$ части).</p><p>В третьем примере нужно выбрать отрезок гор с $$$1$$$ по $$$4$$$, на этом отрезке индекс $$$3$$$ является пиком, поэтому ответ равен $$$2$$$ (всего $$$1$$$ пик, значит дверь разломится на $$$2$$$ части). Можно заметить, что на отрезках $$$[2, 5]$$$, $$$[4, 7]$$$ и $$$[5, 8]$$$ количество пиков также равно $$$1$$$, но у этих отрезков левая граница больше, чем у отрезка $$$[1, 4]$$$, поэтому они не являются правильным ответом.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:01: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:'81249e838ff79d52',t:'MTY5NjY2NTcxOC41NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1341C
1341
C
ru
C. Настя и странный генератор
<div class="problem-statement"><div class="header"><div class="title">C. Настя и странный генератор</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Расстроившись после такого отношения Насти, Денис был очень грустным. Ничего не могло развеселить отвергнутого парня. Чтобы хоть как-то развеселиться он решил побродить по подворотням. И, как ни странно, ему улыбнулась удача! Зайдя в первый двор, он встретил странного человека, который чем-то торговал. </span></p><p>Оглядевшись вокруг, Денис подошел к незнакомцу и купил загадочный товар. Им оказался... Генератор случайных перестановок! Именно это мальчик так давно искал!</p><p>Придя домой он стал изучать, как работает его генератор и узнал алгоритм. Процесс генерации перестановки состоит из $$$n$$$ шагов. На $$$i$$$-м шаге выбирается позиция (индекс) для значения $$$i$$$ $$$(1 \leq i \leq n)$$$. Позиция для значения $$$i$$$ определяется следующим образом:</p><ul> <li> Для всех $$$j$$$ от $$$1$$$ до $$$n$$$ посчитаем $$$r_j$$$  — минимальный такой индекс, что $$$j \leq r_j \leq n$$$, a позиция $$$r_j$$$ еще не занята в перестановке. Если таких позиций нет, то будем считать, что значение $$$r_j$$$ не определено. </li><li> Для всех $$$t$$$ от $$$1$$$ до $$$n$$$ посчитаем $$$count_t$$$  — количество таких позиций $$$1 \leq j \leq n$$$, что значение $$$r_j$$$ определено и $$$r_j = t$$$. </li><li> Рассмотрим все еще не занятые позиции перестановки и среди таких рассмотрим позиции, для которых значение в массиве $$$count$$$ максимально. </li><li> Генератор выбирает одну из таких позиций для значения $$$i$$$. Генератор может выбрать <span class="tex-font-style-bf">любую</span> позицию. </li></ul><p>Рассмотрим работу алгоритма на следующем примере:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/15abb96c35071a49b2b1acdf0082b04b54f18bd6.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Пусть $$$n = 5$$$ и алгоритм уже расставил значения $$$1, 2, 3$$$ в перестановке. Рассмотрим, как генератор будет выбирать позицию для значения $$$4$$$:</p><ul> <li> Значения $$$r$$$ будут $$$r = [3, 3, 3, 4, \times]$$$, где $$$\times$$$ означает неопределенное значение. </li><li> Тогда значения $$$count$$$ будут $$$count = [0, 0, 3, 1, 0]$$$. </li><li> Есть только две не занятые позиции в перестановке: $$$3$$$ и $$$4$$$. Значение в массиве $$$count$$$ для позиции $$$3$$$ равно $$$3$$$, для позиции $$$4$$$ равно $$$1$$$. </li><li> Максимальное значение достигается только для позиции $$$3$$$, поэтому алгоритм однозначно выберет эту позицию для значения $$$4$$$. </li></ul><p>Довольный своим приобретением Денис пошел домой. Несколько дней без перерыва он генерировал перестановки и решил, что преисполнился в осознании процесса генерации. Он считает, что может придумывать случайные перестановки не хуже генератора. </p><p>После этого он выписал первую пришедшую на ум перестановку $$$p_1, p_2, \ldots, p_n$$$ и решил узнать, могла ли она получится в результате работы генератора.</p><p>К сожалению, эта задача оказалась слишком сложна для него, и он обратился за помощью к вам. Нужно определить, могла ли получиться выписанная перестановка применением описанного алгоритма, если генератор всегда выбирает нужную Денису позицию.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ $$$(1 \leq t \leq 10^5)$$$  — количество наборов входных данных в тесте. Далее содержатся сами описания наборов.</p><p>В первой строке каждого набора находится единственное целое число $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — длина перестановки.</p><p>Во второй строке набора находится $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$)  — выписанная Денисом перестановка.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем входным данным не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">Yes</span>», если эта перестановка могла быть получена в результате работы генератора. В противном случае выведите «<span class="tex-font-style-tt">No</span>».</p><p>Все буквы можно выводить в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 2 3 4 5 1 1 1 3 1 3 2 4 4 2 3 1 5 1 5 2 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes No Yes No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Промоделируем работу генератора на первом тесте.</p><p>На $$$1$$$ шаге $$$r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$$$. Максимальное значение достигается в любой свободной позиции, поэтому генератор может выбрать случайную позицию от $$$1$$$ до $$$5$$$. В нашем примере он выбрал $$$5$$$.</p><p>На $$$2$$$ шаге $$$r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]$$$. Максимальное значение достигается в позициях от $$$1$$$ до $$$4$$$, поэтому генератор может выбрать случайную позицию среди них. В нашем примере он выбрал $$$1$$$.</p><p>На $$$3$$$ шаге $$$r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]$$$. Максимальное значение равно $$$2$$$ и достигается только в позиции $$$2$$$, поэтому генератор выберет эту позицию.</p><p>На $$$4$$$ шаге $$$r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]$$$. Максимальное значение равно $$$3$$$ и достигается только в позиции $$$3$$$, поэтому генератор выберет эту позицию.</p><p>На $$$5$$$ шаге $$$r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]$$$. Максимальное значение равно $$$4$$$ и достигается только в позиции $$$4$$$, поэтому генератор выберет эту позицию.</p><p>Итого мы получили перестановку $$$2, 3, 4, 5, 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="475ac903ea91e46cdd8a5f793573f11c"/> <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="e4f8638a89cd11d45a9a414a818e6025d7999ac3"/> <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='475ac903ea91e46cdd8a5f793573f11c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1341%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='475ac903ea91e46cdd8a5f793573f11c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1341">Codeforces Round 637 (Div. 2) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='475ac903ea91e46cdd8a5f793573f11c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1341/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='475ac903ea91e46cdd8a5f793573f11c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599360"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='475ac903ea91e46cdd8a5f793573f11c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599360"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10797:10798" 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/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10812" resourceName="Codeforces Round #637 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/1341">Задачи</a></li> <li><a href="/contest/1341/submit">Отослать</a></li> <li><a href="/contest/1341/my">Мои посылки</a></li> <li><a href="/contest/1341/status">Статус</a></li> <li><a href="/contest/1341/hacks">Взломы</a></li> <li><a href="/contest/1341/room/1">Комната</a></li> <li><a href="/contest/1341/standings">Положение</a></li> <li><a href="/contest/1341/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cbdb8ac3384b8b61076afa2a9d86ce54d58f73c5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Настя и странный генератор</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Расстроившись после такого отношения Насти, Денис был очень грустным. Ничего не могло развеселить отвергнутого парня. Чтобы хоть как-то развеселиться он решил побродить по подворотням. И, как ни странно, ему улыбнулась удача! Зайдя в первый двор, он встретил странного человека, который чем-то торговал. </span></p><p>Оглядевшись вокруг, Денис подошел к незнакомцу и купил загадочный товар. Им оказался... Генератор случайных перестановок! Именно это мальчик так давно искал!</p><p>Придя домой он стал изучать, как работает его генератор и узнал алгоритм. Процесс генерации перестановки состоит из $$$n$$$ шагов. На $$$i$$$-м шаге выбирается позиция (индекс) для значения $$$i$$$ $$$(1 \leq i \leq n)$$$. Позиция для значения $$$i$$$ определяется следующим образом:</p><ul> <li> Для всех $$$j$$$ от $$$1$$$ до $$$n$$$ посчитаем $$$r_j$$$  — минимальный такой индекс, что $$$j \leq r_j \leq n$$$, a позиция $$$r_j$$$ еще не занята в перестановке. Если таких позиций нет, то будем считать, что значение $$$r_j$$$ не определено. </li><li> Для всех $$$t$$$ от $$$1$$$ до $$$n$$$ посчитаем $$$count_t$$$  — количество таких позиций $$$1 \leq j \leq n$$$, что значение $$$r_j$$$ определено и $$$r_j = t$$$. </li><li> Рассмотрим все еще не занятые позиции перестановки и среди таких рассмотрим позиции, для которых значение в массиве $$$count$$$ максимально. </li><li> Генератор выбирает одну из таких позиций для значения $$$i$$$. Генератор может выбрать <span class="tex-font-style-bf">любую</span> позицию. </li></ul><p>Рассмотрим работу алгоритма на следующем примере:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/15abb96c35071a49b2b1acdf0082b04b54f18bd6.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Пусть $$$n = 5$$$ и алгоритм уже расставил значения $$$1, 2, 3$$$ в перестановке. Рассмотрим, как генератор будет выбирать позицию для значения $$$4$$$:</p><ul> <li> Значения $$$r$$$ будут $$$r = [3, 3, 3, 4, \times]$$$, где $$$\times$$$ означает неопределенное значение. </li><li> Тогда значения $$$count$$$ будут $$$count = [0, 0, 3, 1, 0]$$$. </li><li> Есть только две не занятые позиции в перестановке: $$$3$$$ и $$$4$$$. Значение в массиве $$$count$$$ для позиции $$$3$$$ равно $$$3$$$, для позиции $$$4$$$ равно $$$1$$$. </li><li> Максимальное значение достигается только для позиции $$$3$$$, поэтому алгоритм однозначно выберет эту позицию для значения $$$4$$$. </li></ul><p>Довольный своим приобретением Денис пошел домой. Несколько дней без перерыва он генерировал перестановки и решил, что преисполнился в осознании процесса генерации. Он считает, что может придумывать случайные перестановки не хуже генератора. </p><p>После этого он выписал первую пришедшую на ум перестановку $$$p_1, p_2, \ldots, p_n$$$ и решил узнать, могла ли она получится в результате работы генератора.</p><p>К сожалению, эта задача оказалась слишком сложна для него, и он обратился за помощью к вам. Нужно определить, могла ли получиться выписанная перестановка применением описанного алгоритма, если генератор всегда выбирает нужную Денису позицию.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ $$$(1 \leq t \leq 10^5)$$$  — количество наборов входных данных в тесте. Далее содержатся сами описания наборов.</p><p>В первой строке каждого набора находится единственное целое число $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — длина перестановки.</p><p>Во второй строке набора находится $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$)  — выписанная Денисом перестановка.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем входным данным не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">Yes</span>», если эта перестановка могла быть получена в результате работы генератора. В противном случае выведите «<span class="tex-font-style-tt">No</span>».</p><p>Все буквы можно выводить в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 2 3 4 5 1 1 1 3 1 3 2 4 4 2 3 1 5 1 5 2 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes No Yes No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Промоделируем работу генератора на первом тесте.</p><p>На $$$1$$$ шаге $$$r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$$$. Максимальное значение достигается в любой свободной позиции, поэтому генератор может выбрать случайную позицию от $$$1$$$ до $$$5$$$. В нашем примере он выбрал $$$5$$$.</p><p>На $$$2$$$ шаге $$$r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]$$$. Максимальное значение достигается в позициях от $$$1$$$ до $$$4$$$, поэтому генератор может выбрать случайную позицию среди них. В нашем примере он выбрал $$$1$$$.</p><p>На $$$3$$$ шаге $$$r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]$$$. Максимальное значение равно $$$2$$$ и достигается только в позиции $$$2$$$, поэтому генератор выберет эту позицию.</p><p>На $$$4$$$ шаге $$$r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]$$$. Максимальное значение равно $$$3$$$ и достигается только в позиции $$$3$$$, поэтому генератор выберет эту позицию.</p><p>На $$$5$$$ шаге $$$r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]$$$. Максимальное значение равно $$$4$$$ и достигается только в позиции $$$4$$$, поэтому генератор выберет эту позицию.</p><p>Итого мы получили перестановку $$$2, 3, 4, 5, 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 11:02: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:'81249e8cef1600a5',t:'MTY5NjY2NTcyMC4xMDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1500"]
1341D
1341
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"> Денис, справившийся с покупкой цветов и конфет (об этой истории вы узнаете в следующей задаче), поехал на встречу с Настей, чтобы предложить ей стать парой. </span></p><p><span class="tex-font-style-it"> И вот, они сидят вместе в кафе, болтают. Решительный Денис наконец-то предлагает быть им вместе, но... Но Настя не даёт никакого ответа. </span></p><p>Как же сильно расстроился бедный парень. Так сильно, что он пнул какое-то табло с цифрами. Цифры отображаются таким же образом, как на электронных часах: каждая позиция для цифры состоит из $$$7$$$ сегментов, которые могут быть включены или выключены, чтобы отображать различные цифры. На картинке показано, как изображаются все $$$10$$$ десятичных цифр: </p><center> <img class="tex-graphics" height="113px" src="https://espresso.codeforces.com/19e4ae06aceef4b9326d2ef6bca3339f5c84ed91.png" style="max-width: 100.0%;max-height: 100.0%;" width="378px"/> </center> После пинка некоторые палочки перестали работать, то есть некоторые палочки могли перестать гореть, если горели раньше. Но Денис запомнил, сколько палочек горело и сколько горит сейчас. Пусть сломалось <span class="tex-font-style-bf">ровно</span> $$$k$$$ палочек и известно, какие палочки горят сейчас. Денис задался вопросом: какое максимальное число может гореть на табло, если включить ровно $$$k$$$ палочек (из тех которые сейчас выключены)? <p><span class="tex-font-style-bf">Разрешается</span>, чтобы в числе были лидирующие нули.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано число $$$n$$$ $$$(1 \leq n \leq 2000)$$$  — количество цифр на табло и $$$k$$$ $$$(0 \leq k \leq 2000)$$$  — количество сломанных палочек.</p><p>В следующих $$$n$$$ строках находится по одной бинарной строке длины $$$7$$$, $$$i$$$-я из которых кодирует $$$i$$$-ю цифру табло.</p><p>Каждая цифра на табло состоит из $$$7$$$ палочек. Пронумеруем их, как на картинке ниже, и пусть на $$$i$$$-м месте бинарной строки будет $$$0$$$, если $$$i$$$-я палочка не горит и $$$1$$$, если горит. Тогда бинарная строка длины $$$7$$$ будет задавать то, какие палочки горят.</p><center> <img class="tex-graphics" height="265px" src="https://espresso.codeforces.com/bed1234ad2f319542a635519d6e40510e65f641b.png" style="max-width: 100.0%;max-height: 100.0%;" width="189px"/> </center><p>Таким образом, последовательности «1110111», «0010010», «1011101», «1011011», «0111010», «1101011», «1101111», «1010010», «1111111», «1111011» кодируют по порядку все цифры от $$$0$$$ до $$$9$$$ включительно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число, состоящее из $$$n$$$ разрядов – максимальное число, которое можно получить, если включить ровно $$$k$$$ палочек или $$$-1$$$, если невозможно так включить ровно $$$k$$$ палочек, чтобы на табло получилась какая-то последовательность цифр.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 7 0000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 5 0010010 0010010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 97</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 0100001 1001001 1010011 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте мы обязаны включить все $$$7$$$ палочек и получить на табло одну цифру $$$8$$$.</p><p>Во втором тесте у нас включены палочки таким образом, что образуются единицы. За $$$5$$$ дополнительно включённых палочек можно получить числа $$$07$$$, $$$18$$$, $$$34$$$, $$$43$$$, $$$70$$$, $$$79$$$, $$$81$$$ и $$$97$$$, из них выбираем максимальное  — $$$97$$$.</p><p>В третьем тесте невозможно так включить ровно $$$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="16de265ad94269ceb1522496a7eafd16"/> <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="e4f8638a89cd11d45a9a414a818e6025d7999ac3"/> <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='16de265ad94269ceb1522496a7eafd16'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1341%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='16de265ad94269ceb1522496a7eafd16'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1341">Codeforces Round 637 (Div. 2) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='16de265ad94269ceb1522496a7eafd16'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1341/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='16de265ad94269ceb1522496a7eafd16'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599361"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='16de265ad94269ceb1522496a7eafd16'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599361"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10797:10798" 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/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10812" resourceName="Codeforces Round #637 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/1341">Задачи</a></li> <li><a href="/contest/1341/submit">Отослать</a></li> <li><a href="/contest/1341/my">Мои посылки</a></li> <li><a href="/contest/1341/status">Статус</a></li> <li><a href="/contest/1341/hacks">Взломы</a></li> <li><a href="/contest/1341/room/1">Комната</a></li> <li><a href="/contest/1341/standings">Положение</a></li> <li><a href="/contest/1341/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4ed858a6544bfd51e3d5a0068665fb5bef1520fa"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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"> Денис, справившийся с покупкой цветов и конфет (об этой истории вы узнаете в следующей задаче), поехал на встречу с Настей, чтобы предложить ей стать парой. </span></p><p><span class="tex-font-style-it"> И вот, они сидят вместе в кафе, болтают. Решительный Денис наконец-то предлагает быть им вместе, но... Но Настя не даёт никакого ответа. </span></p><p>Как же сильно расстроился бедный парень. Так сильно, что он пнул какое-то табло с цифрами. Цифры отображаются таким же образом, как на электронных часах: каждая позиция для цифры состоит из $$$7$$$ сегментов, которые могут быть включены или выключены, чтобы отображать различные цифры. На картинке показано, как изображаются все $$$10$$$ десятичных цифр: </p><center> <img class="tex-graphics" height="113px" src="https://espresso.codeforces.com/19e4ae06aceef4b9326d2ef6bca3339f5c84ed91.png" style="max-width: 100.0%;max-height: 100.0%;" width="378px" /> </center> После пинка некоторые палочки перестали работать, то есть некоторые палочки могли перестать гореть, если горели раньше. Но Денис запомнил, сколько палочек горело и сколько горит сейчас. Пусть сломалось <span class="tex-font-style-bf">ровно</span> $$$k$$$ палочек и известно, какие палочки горят сейчас. Денис задался вопросом: какое максимальное число может гореть на табло, если включить ровно $$$k$$$ палочек (из тех которые сейчас выключены)? <p><span class="tex-font-style-bf">Разрешается</span>, чтобы в числе были лидирующие нули.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано число $$$n$$$ $$$(1 \leq n \leq 2000)$$$  — количество цифр на табло и $$$k$$$ $$$(0 \leq k \leq 2000)$$$  — количество сломанных палочек.</p><p>В следующих $$$n$$$ строках находится по одной бинарной строке длины $$$7$$$, $$$i$$$-я из которых кодирует $$$i$$$-ю цифру табло.</p><p>Каждая цифра на табло состоит из $$$7$$$ палочек. Пронумеруем их, как на картинке ниже, и пусть на $$$i$$$-м месте бинарной строки будет $$$0$$$, если $$$i$$$-я палочка не горит и $$$1$$$, если горит. Тогда бинарная строка длины $$$7$$$ будет задавать то, какие палочки горят.</p><center> <img class="tex-graphics" height="265px" src="https://espresso.codeforces.com/bed1234ad2f319542a635519d6e40510e65f641b.png" style="max-width: 100.0%;max-height: 100.0%;" width="189px" /> </center><p>Таким образом, последовательности «1110111», «0010010», «1011101», «1011011», «0111010», «1101011», «1101111», «1010010», «1111111», «1111011» кодируют по порядку все цифры от $$$0$$$ до $$$9$$$ включительно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число, состоящее из $$$n$$$ разрядов – максимальное число, которое можно получить, если включить ровно $$$k$$$ палочек или $$$-1$$$, если невозможно так включить ровно $$$k$$$ палочек, чтобы на табло получилась какая-то последовательность цифр.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 7 0000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 5 0010010 0010010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 97</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 0100001 1001001 1010011 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте мы обязаны включить все $$$7$$$ палочек и получить на табло одну цифру $$$8$$$.</p><p>Во втором тесте у нас включены палочки таким образом, что образуются единицы. За $$$5$$$ дополнительно включённых палочек можно получить числа $$$07$$$, $$$18$$$, $$$34$$$, $$$43$$$, $$$70$$$, $$$79$$$, $$$81$$$ и $$$97$$$, из них выбираем максимальное  — $$$97$$$.</p><p>В третьем тесте невозможно так включить ровно $$$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 11:02: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:'81249e96498e76ad',t:'MTY5NjY2NTcyMS42ODQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1700"]
1341E
1341
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$$$ полос, перейти которую за один зеленый свет не всегда возможно. Предвидя это, добрый мэр распорядился поставить в некоторых точках этой дороги островки безопасности. Каждый островок расположен после какой-то полосы, а также в начале и в конце дороги. На них пешеходы могут отдохнуть, набраться сил и дождаться зеленого света.</p><p>Денис подошел к левому краю дороги ровно в тот момент, когда загорелся зеленый свет. Мальчик знает, что светофор сначала горит $$$g$$$ секунд зеленым, а потом $$$r$$$ секунд красным, потом опять $$$g$$$ секунд зеленым и так далее.</p><p>Формально, дорогу можно представить как отрезок $$$[0, n]$$$. Изначально Денис стоит в точке $$$0$$$. Его задача - попасть в точку $$$n$$$ за минимальное возможное время.</p><p>Oн знает множество различных целых чисел $$$d_1, d_2, \ldots, d_m$$$, где $$$0 \leq d_i \leq n$$$  — координаты точек, в которых расположены островки безопасности. Только в одной из этих точек мальчик может находиться в момент, когда горит красный свет.</p><p>К сожалению, из-за волнения Денис не всегда может контролировать себя, поэтому сейчас на его передвижения наложены некоторые ограничения:</p><ul> <li> Он обязан двигаться всегда, пока горит зеленый, ведь сложно стоять, когда тебя ждет такая девушка. Денис за $$$1$$$ секунду может изменить свое положение на $$$\pm 1$$$. При этом он должен всегда оставаться внутри отрезка $$$[0, n]$$$. </li><li> Он может менять направление движения только на островках безопасности (ведь это безопасно). Это означает, что если за предыдущую секунду мальчик изменил свое положение на $$$+1$$$, то если он находится на островке безопасности, он может изменить свое положение на $$$\pm 1$$$, иначе он может изменить свое положение вновь только на $$$+1$$$. Аналогично, если за предыдущую секунду он изменил свое положение на $$$-1$$$, на островке безопасности он может изменить свое положение на $$$\pm 1$$$, а в любой другой точке вновь только на $$$-1$$$. </li><li> В момент, когда загорается красный, мальчик должен оказаться на каком-то островке безопасности. Он сможет продолжить движение в любом направлении, когда вновь загорится зеленый. </li></ul><p>Считается, что Денис перешел дорогу как только его координата станет равна $$$n$$$.</p><p>Эта задача оказалась не так проста, ведь возможно, таким способом даже невозможно перейти дорогу. Так как у Дениса все мысли о любви, он не справился решить ее и попросил нас помочь ему в этом. Найдите минимальное возможное время, за которое он сможет перейти дорогу по таким правилам, либо установите, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$  — ширина дороги и количество островков безопасности.</p><p>Во второй строке находится $$$m$$$ различных целых чисел $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$  — точки, в которых расположены островки безопасности. Гарантируется, что среди них есть $$$0$$$ и $$$n$$$.</p><p>В третьей строке находится два целых числа $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$  — время, которое на светофоре горит зеленый свет и время, которое на светофоре горит красный свет.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число  — минимальное время, за которое Денис может перейти дорогу по всем правилам. </p><p>Если перейти дорогу по всем правилам невозможно выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 15 5 0 3 7 14 15 11 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 45</pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 4 0 3 7 13 9 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>В первом тесте оптимальный маршрут такой: </p><ul> <li> за первый зеленый свет дойти до $$$7$$$ и вернуться на $$$3$$$. В этом случае, мы сменим направление движения в точке $$$7$$$, что разрешено, поскольку в этой точке есть островок безопасности. В конце мы окажемся в точке $$$3$$$, где также есть островок безопасности. Следующие $$$11$$$ секунд мы должны подождать красный свет. </li><li> за второй зеленый свет дойти до $$$14$$$. Снова подождать красный свет. </li><li> за $$$1$$$ секунду перейти в $$$15$$$. В итоге Денис оказывается в конце дороги. </li></ul><p>Всего получается $$$45$$$ секунд.</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="ecfbf716d8b6f811fc3d521eeede855b"/> <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="e4f8638a89cd11d45a9a414a818e6025d7999ac3"/> <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='ecfbf716d8b6f811fc3d521eeede855b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1341%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='ecfbf716d8b6f811fc3d521eeede855b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1341">Codeforces Round 637 (Div. 2) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='ecfbf716d8b6f811fc3d521eeede855b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1341/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='ecfbf716d8b6f811fc3d521eeede855b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599362"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ecfbf716d8b6f811fc3d521eeede855b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599362"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10797:10798" 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/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10812" resourceName="Codeforces Round #637 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/1341">Задачи</a></li> <li><a href="/contest/1341/submit">Отослать</a></li> <li><a href="/contest/1341/my">Мои посылки</a></li> <li><a href="/contest/1341/status">Статус</a></li> <li><a href="/contest/1341/hacks">Взломы</a></li> <li><a href="/contest/1341/room/1">Комната</a></li> <li><a href="/contest/1341/standings">Положение</a></li> <li><a href="/contest/1341/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5b636e6bd173c52ac44e8a2b7b32942cc4fbcf4d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ полос, перейти которую за один зеленый свет не всегда возможно. Предвидя это, добрый мэр распорядился поставить в некоторых точках этой дороги островки безопасности. Каждый островок расположен после какой-то полосы, а также в начале и в конце дороги. На них пешеходы могут отдохнуть, набраться сил и дождаться зеленого света.</p><p>Денис подошел к левому краю дороги ровно в тот момент, когда загорелся зеленый свет. Мальчик знает, что светофор сначала горит $$$g$$$ секунд зеленым, а потом $$$r$$$ секунд красным, потом опять $$$g$$$ секунд зеленым и так далее.</p><p>Формально, дорогу можно представить как отрезок $$$[0, n]$$$. Изначально Денис стоит в точке $$$0$$$. Его задача - попасть в точку $$$n$$$ за минимальное возможное время.</p><p>Oн знает множество различных целых чисел $$$d_1, d_2, \ldots, d_m$$$, где $$$0 \leq d_i \leq n$$$  — координаты точек, в которых расположены островки безопасности. Только в одной из этих точек мальчик может находиться в момент, когда горит красный свет.</p><p>К сожалению, из-за волнения Денис не всегда может контролировать себя, поэтому сейчас на его передвижения наложены некоторые ограничения:</p><ul> <li> Он обязан двигаться всегда, пока горит зеленый, ведь сложно стоять, когда тебя ждет такая девушка. Денис за $$$1$$$ секунду может изменить свое положение на $$$\pm 1$$$. При этом он должен всегда оставаться внутри отрезка $$$[0, n]$$$. </li><li> Он может менять направление движения только на островках безопасности (ведь это безопасно). Это означает, что если за предыдущую секунду мальчик изменил свое положение на $$$+1$$$, то если он находится на островке безопасности, он может изменить свое положение на $$$\pm 1$$$, иначе он может изменить свое положение вновь только на $$$+1$$$. Аналогично, если за предыдущую секунду он изменил свое положение на $$$-1$$$, на островке безопасности он может изменить свое положение на $$$\pm 1$$$, а в любой другой точке вновь только на $$$-1$$$. </li><li> В момент, когда загорается красный, мальчик должен оказаться на каком-то островке безопасности. Он сможет продолжить движение в любом направлении, когда вновь загорится зеленый. </li></ul><p>Считается, что Денис перешел дорогу как только его координата станет равна $$$n$$$.</p><p>Эта задача оказалась не так проста, ведь возможно, таким способом даже невозможно перейти дорогу. Так как у Дениса все мысли о любви, он не справился решить ее и попросил нас помочь ему в этом. Найдите минимальное возможное время, за которое он сможет перейти дорогу по таким правилам, либо установите, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$  — ширина дороги и количество островков безопасности.</p><p>Во второй строке находится $$$m$$$ различных целых чисел $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$  — точки, в которых расположены островки безопасности. Гарантируется, что среди них есть $$$0$$$ и $$$n$$$.</p><p>В третьей строке находится два целых числа $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$  — время, которое на светофоре горит зеленый свет и время, которое на светофоре горит красный свет.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число  — минимальное время, за которое Денис может перейти дорогу по всем правилам. </p><p>Если перейти дорогу по всем правилам невозможно выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 15 5 0 3 7 14 15 11 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 45</pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 4 0 3 7 13 9 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>В первом тесте оптимальный маршрут такой: </p><ul> <li> за первый зеленый свет дойти до $$$7$$$ и вернуться на $$$3$$$. В этом случае, мы сменим направление движения в точке $$$7$$$, что разрешено, поскольку в этой точке есть островок безопасности. В конце мы окажемся в точке $$$3$$$, где также есть островок безопасности. Следующие $$$11$$$ секунд мы должны подождать красный свет. </li><li> за второй зеленый свет дойти до $$$14$$$. Снова подождать красный свет. </li><li> за $$$1$$$ секунду перейти в $$$15$$$. В итоге Денис оказывается в конце дороги. </li></ul><p>Всего получается $$$45$$$ секунд.</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 11:02: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:'81249ea04e2a16fe',t:'MTY5NjY2NTcyMy4yMDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2400"]
1341F
1341
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><span class="tex-font-style-it">Придя к Насте, Денис обнаружил, что она ему не рада... Но у молодого человека есть последняя надежда. Он хочет купить все вещи, что нравятся Насте. Тогда-то она уж точно согласится с ним общаться.</span></p><p>Карта города, в котором живут наши герои, представляет собой множество площадей, некоторые из которых соединены дорогами. От любой площади можно добраться до любой другой ровно одним способом, используя эти дороги и не посещая одну и ту же площадь дважды. Получается, что граф города  — это дерево.</p><p>Денис находится в вершине $$$1$$$ в момент времени $$$0$$$. Он хочет хоть раз побывать в каждой вершине и вернуться назад как можно раньше.</p><p>Денис может проходить вдоль любой дороги за $$$1$$$ времени. Увы, город столь велик, что сделать это быстро никак не выйдет. Поэтому Денис пошел на отчаянный шаг. Он достал свою карманную машину времени, которую он собрал у себя в подвале. С ее помощью Денис может стоя на месте сменить время на любое неотрицательное время, которое меньше текущего. </p><p>Но у машины времени есть один нюанс. Если герой окажется в одном месте и в одно и то же время дважды, произойдет взрыв вселенских масштабов и не получится порадовать Настю. Поэтому Денис просит вас проложить ему маршрут с использованием машины времени такой, что он обойдет все площади и вернется на первую и при этом максимальное время в котором он побывал будет минимально.</p><p>Формально, маршрут Дениса можно представить как последовательность пар $$$\{v_1, t_1\}, \{v_2, t_2\}, \{v_3, t_3\}, \ldots, \{v_k, t_k\}$$$, где $$$v_i$$$ — номер площади, а $$$t_i$$$  — время, в котором сейчас находится мальчик.</p><p>Должны быть выполнены следующие условия:</p><ul> <li> Маршрут начинается на площади $$$1$$$ в момент времени $$$0$$$, то есть $$$v_1 = 1, t_1 = 0$$$ и заканчивается на площади $$$1$$$, то есть $$$v_k = 1$$$. </li><li> Все переходы делятся на два типа: <ol> <li> Стоя на площади сменить время: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \} : v_{i+1} = v_i, 0 \leq t_{i+1} &lt; t_i$$$. </li><li> Пройти по одной из дорог: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \}$$$. При этом $$$v_i$$$ и $$$v_{i+1}$$$ соединены дорогой и $$$t_{i+1} = t_i + 1$$$. </li></ol> </li><li> Все пары $$$\{ v_i, t_i \}$$$ должны быть различны. </li><li> Среди $$$v_1, v_2, \ldots, v_k$$$ встречаются все площади. </li></ul><p>Вам нужно найти маршрут такой, что максимальное время, в котором побывает Денис будет минимальным, то есть маршрут, для которого $$$\max{(t_1, t_2, \ldots, t_k)}$$$ будет минимально возможным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — количество площадей в городе.</p><p>В следующих $$$n - 1$$$ строках находится по два целых числа $$$u$$$ и $$$v$$$ $$$(1 \leq v, u \leq n, u \neq v)$$$  — номера площадей, соединенных дорогой.</p><p>Гарантируется, что заданный граф является деревом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$k$$$ $$$(1 \leq k \leq 10^6)$$$  — длина пути Дениса.</p><p>В следующих $$$k$$$ строках выведите пары $$$v_i, t_i$$$  — пары, описывающие маршрут Дениса (как в условии).</p><p>Все требования к маршруту, описанные в условии должны быть выполнены.</p><p>Гарантируется, что при заданных ограничениях существует хотя бы один маршрут и ответ, длина которого не превосходит $$$10^6$$$. Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 2 3 2 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 13 1 0 2 1 3 2 3 1 2 2 4 3 4 1 5 2 5 1 4 2 2 3 2 0 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="c95b4f2cf265d6e031252327a7818143"/> <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="e4f8638a89cd11d45a9a414a818e6025d7999ac3"/> <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='c95b4f2cf265d6e031252327a7818143'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1341%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='c95b4f2cf265d6e031252327a7818143'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1341">Codeforces Round 637 (Div. 2) - Thanks, Ivan Belonogov!</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='c95b4f2cf265d6e031252327a7818143'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1341/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='c95b4f2cf265d6e031252327a7818143'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599364"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c95b4f2cf265d6e031252327a7818143'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599364"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76348" title="Codeforces Round #637 — Thanks, Ivan Belonogov!" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10797:10798" 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/76479" title="Codeforces Round #637 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10812" resourceName="Codeforces Round #637 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/1341">Задачи</a></li> <li><a href="/contest/1341/submit">Отослать</a></li> <li><a href="/contest/1341/my">Мои посылки</a></li> <li><a href="/contest/1341/status">Статус</a></li> <li><a href="/contest/1341/hacks">Взломы</a></li> <li><a href="/contest/1341/room/1">Комната</a></li> <li><a href="/contest/1341/standings">Положение</a></li> <li><a href="/contest/1341/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_dcff82842a303293cce62395297282acdc966050"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><span class="tex-font-style-it">Придя к Насте, Денис обнаружил, что она ему не рада... Но у молодого человека есть последняя надежда. Он хочет купить все вещи, что нравятся Насте. Тогда-то она уж точно согласится с ним общаться.</span></p><p>Карта города, в котором живут наши герои, представляет собой множество площадей, некоторые из которых соединены дорогами. От любой площади можно добраться до любой другой ровно одним способом, используя эти дороги и не посещая одну и ту же площадь дважды. Получается, что граф города  — это дерево.</p><p>Денис находится в вершине $$$1$$$ в момент времени $$$0$$$. Он хочет хоть раз побывать в каждой вершине и вернуться назад как можно раньше.</p><p>Денис может проходить вдоль любой дороги за $$$1$$$ времени. Увы, город столь велик, что сделать это быстро никак не выйдет. Поэтому Денис пошел на отчаянный шаг. Он достал свою карманную машину времени, которую он собрал у себя в подвале. С ее помощью Денис может стоя на месте сменить время на любое неотрицательное время, которое меньше текущего. </p><p>Но у машины времени есть один нюанс. Если герой окажется в одном месте и в одно и то же время дважды, произойдет взрыв вселенских масштабов и не получится порадовать Настю. Поэтому Денис просит вас проложить ему маршрут с использованием машины времени такой, что он обойдет все площади и вернется на первую и при этом максимальное время в котором он побывал будет минимально.</p><p>Формально, маршрут Дениса можно представить как последовательность пар $$$\{v_1, t_1\}, \{v_2, t_2\}, \{v_3, t_3\}, \ldots, \{v_k, t_k\}$$$, где $$$v_i$$$ — номер площади, а $$$t_i$$$  — время, в котором сейчас находится мальчик.</p><p>Должны быть выполнены следующие условия:</p><ul> <li> Маршрут начинается на площади $$$1$$$ в момент времени $$$0$$$, то есть $$$v_1 = 1, t_1 = 0$$$ и заканчивается на площади $$$1$$$, то есть $$$v_k = 1$$$. </li><li> Все переходы делятся на два типа: <ol> <li> Стоя на площади сменить время: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \} : v_{i+1} = v_i, 0 \leq t_{i+1} &lt; t_i$$$. </li><li> Пройти по одной из дорог: $$$\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \}$$$. При этом $$$v_i$$$ и $$$v_{i+1}$$$ соединены дорогой и $$$t_{i+1} = t_i + 1$$$. </li></ol> </li><li> Все пары $$$\{ v_i, t_i \}$$$ должны быть различны. </li><li> Среди $$$v_1, v_2, \ldots, v_k$$$ встречаются все площади. </li></ul><p>Вам нужно найти маршрут такой, что максимальное время, в котором побывает Денис будет минимальным, то есть маршрут, для которого $$$\max{(t_1, t_2, \ldots, t_k)}$$$ будет минимально возможным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — количество площадей в городе.</p><p>В следующих $$$n - 1$$$ строках находится по два целых числа $$$u$$$ и $$$v$$$ $$$(1 \leq v, u \leq n, u \neq v)$$$  — номера площадей, соединенных дорогой.</p><p>Гарантируется, что заданный граф является деревом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$k$$$ $$$(1 \leq k \leq 10^6)$$$  — длина пути Дениса.</p><p>В следующих $$$k$$$ строках выведите пары $$$v_i, t_i$$$  — пары, описывающие маршрут Дениса (как в условии).</p><p>Все требования к маршруту, описанные в условии должны быть выполнены.</p><p>Гарантируется, что при заданных ограничениях существует хотя бы один маршрут и ответ, длина которого не превосходит $$$10^6$$$. Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 2 3 2 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 13 1 0 2 1 3 2 3 1 2 2 4 3 4 1 5 2 5 1 4 2 2 3 2 0 1 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:02: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:'81249ea9af593aa7',t:'MTY5NjY2NTcyNC41MzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2600"]
1342A
1342
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$$$ и $$$y$$$. Вы можете выполнять операции двух типов: </p><ol> <li> Заплатить $$$a$$$ долларов и увеличить либо уменьшить любое из чисел на $$$1$$$. Например, если $$$x = 0$$$ и $$$y = 7$$$ возможны четыре варианта после такой операции: <ul> <li> $$$x = 0$$$, $$$y = 6$$$; </li><li> $$$x = 0$$$, $$$y = 8$$$; </li><li> $$$x = -1$$$, $$$y = 7$$$; </li><li> $$$x = 1$$$, $$$y = 7$$$. </li></ul><p> </p></li><li> Заплатить $$$b$$$ долларов и увеличить либо уменьшить оба числа на $$$1$$$. Например, если $$$x = 0$$$ и $$$y = 7$$$ возможны два варианта после такой операции: <ul> <li> $$$x = -1$$$, $$$y = 6$$$; </li><li> $$$x = 1$$$, $$$y = 8$$$. </li></ul> </li></ol><p>Ваша задача сделать оба числа равными нулю одновременно, т.е. достичь состояния $$$x = y = 0$$$. Других каких-либо требований нет. В частности, переход из $$$x=1$$$, $$$y=0$$$ в $$$x=y=0$$$ допустим.</p><p>Посчитайте минимально количество долларов, которое вам нужно потратить для этого.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два числа $$$x$$$ и $$$y$$$ ($$$0 \le x, y \le 10^9$$$).</p><p>Вторая строка каждого набора входных данных содержит два числа $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ — минимальное количество долларов, которое придется потратить.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 3 391 555 0 0 9 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1337 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы можете применить следующие операции: первую, вторую и первую. Таким образом, вы потратите $$$391 + 555 + 391 = 1337$$$ долларов.</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="27816e7109ce740ab211bcb720637c1b"/> <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="db4c5554a97fc92b10b3a4d69207641a29a444f5"/> <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='27816e7109ce740ab211bcb720637c1b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1342%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='27816e7109ce740ab211bcb720637c1b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1342">Educational Codeforces Round 86 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='27816e7109ce740ab211bcb720637c1b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1342/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='27816e7109ce740ab211bcb720637c1b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="604756"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='27816e7109ce740ab211bcb720637c1b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="604756"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76526" title="76526" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12608" resourceName="76526" resourceManual="true" src="//codeforces.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/76633" title="76633" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12607" resourceName="76633" resourceManual="true" src="//codeforces.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/1342">Задачи</a></li> <li><a href="/contest/1342/submit">Отослать</a></li> <li><a href="/contest/1342/my">Мои посылки</a></li> <li><a href="/contest/1342/status">Статус</a></li> <li><a href="/contest/1342/hacks">Взломы</a></li> <li><a href="/contest/1342/standings">Положение</a></li> <li><a href="/contest/1342/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_614fc61e9885b17ed747a471775f2eca88537c0b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ и $$$y$$$. Вы можете выполнять операции двух типов: </p><ol> <li> Заплатить $$$a$$$ долларов и увеличить либо уменьшить любое из чисел на $$$1$$$. Например, если $$$x = 0$$$ и $$$y = 7$$$ возможны четыре варианта после такой операции: <ul> <li> $$$x = 0$$$, $$$y = 6$$$; </li><li> $$$x = 0$$$, $$$y = 8$$$; </li><li> $$$x = -1$$$, $$$y = 7$$$; </li><li> $$$x = 1$$$, $$$y = 7$$$. </li></ul><p> </p></li><li> Заплатить $$$b$$$ долларов и увеличить либо уменьшить оба числа на $$$1$$$. Например, если $$$x = 0$$$ и $$$y = 7$$$ возможны два варианта после такой операции: <ul> <li> $$$x = -1$$$, $$$y = 6$$$; </li><li> $$$x = 1$$$, $$$y = 8$$$. </li></ul> </li></ol><p>Ваша задача сделать оба числа равными нулю одновременно, т.е. достичь состояния $$$x = y = 0$$$. Других каких-либо требований нет. В частности, переход из $$$x=1$$$, $$$y=0$$$ в $$$x=y=0$$$ допустим.</p><p>Посчитайте минимально количество долларов, которое вам нужно потратить для этого.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два числа $$$x$$$ и $$$y$$$ ($$$0 \le x, y \le 10^9$$$).</p><p>Вторая строка каждого набора входных данных содержит два числа $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ — минимальное количество долларов, которое придется потратить.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 3 391 555 0 0 9 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1337 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы можете применить следующие операции: первую, вторую и первую. Таким образом, вы потратите $$$391 + 555 + 391 = 1337$$$ долларов.</p><p>Во втором наборе входных данных оба числа равны нулю изначально, а значит вам не нужно ничего тратить.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'81249eb20e1a1490',t:'MTY5NjY2NTcyNS45MDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1000"]
1342B
1342
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$$$ имеет период $$$k$$$, если $$$s_i = s_{i + k}$$$ для всех $$$i$$$ от $$$1$$$ по $$$|s| - k$$$ ($$$|s|$$$ — это длина строки $$$s$$$), и $$$k$$$ — минимальное положительное целое число с этим свойством.</p><p>Несколько примеров вычисления периода: для $$$s$$$=«<span class="tex-font-style-tt">0101</span>» период равен $$$k=2$$$, для $$$s$$$=«<span class="tex-font-style-tt">0000</span>» период равен $$$k=1$$$, для $$$s$$$=«<span class="tex-font-style-tt">010</span>» период равен $$$k=2$$$, для $$$s$$$=«<span class="tex-font-style-tt">0011</span>» период равен $$$k=4$$$. </p><p>Вам задана строка $$$t$$$, состоящая только из <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>, и вам нужно найти такую строку $$$s$$$, что:</p><ol> <li> Строка $$$s$$$ состоит только из <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>; </li><li> Длина $$$s$$$ не превосходит $$$2 \cdot |t|$$$; </li><li> Строка $$$t$$$ является подпоследовательностью строки $$$s$$$; </li><li> Строка $$$s$$$ имеет минимальный возможный период среди всех строк, удовлетворяющих условиям 1—3. </li></ol><p>Напомним, что $$$t$$$ является подпоследовательностью $$$s$$$, если $$$t$$$ можно получить из $$$s$$$ путем удаления нуля или более элементов (любых) и не меняя порядок оставшихся элементов. Например, $$$t$$$=«<span class="tex-font-style-tt">011</span>» — это подпоследовательность строки $$$s$$$=«<span class="tex-font-style-tt">10101</span>».</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество наборов входных данных.</p><p>В следующих $$$T$$$ строках заданы сами наборы — по одному на строку. В каждой строке задана строка $$$t$$$ ($$$1 \le |t| \le 100$$$), состоящая только из <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите по одной строке на каждый набор входных данных — строку $$$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 00 01 111 110 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00 01 11111 1010</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и втором наборе $$$s = t$$$, так как это уже одни из оптимальных решений. Периоды ответов равны $$$1$$$ и $$$2$$$, соответственно.</p><p>В третьем наборе, есть и другие более короткие ответы, но все в порядке, потому что не требуется минимизировать ответ $$$s$$$. Строка $$$s$$$ имеет период $$$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="2d7ad5f75a21aa76c5b4359a8b1a7d0d"/> <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="db4c5554a97fc92b10b3a4d69207641a29a444f5"/> <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='2d7ad5f75a21aa76c5b4359a8b1a7d0d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1342%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='2d7ad5f75a21aa76c5b4359a8b1a7d0d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1342">Educational Codeforces Round 86 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='2d7ad5f75a21aa76c5b4359a8b1a7d0d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1342/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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="Сложность"> *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='2d7ad5f75a21aa76c5b4359a8b1a7d0d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="604757"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2d7ad5f75a21aa76c5b4359a8b1a7d0d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="604757"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76526" title="76526" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12608" resourceName="76526" resourceManual="true" src="//codeforces.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/76633" title="76633" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12607" resourceName="76633" resourceManual="true" src="//codeforces.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/1342">Задачи</a></li> <li><a href="/contest/1342/submit">Отослать</a></li> <li><a href="/contest/1342/my">Мои посылки</a></li> <li><a href="/contest/1342/status">Статус</a></li> <li><a href="/contest/1342/hacks">Взломы</a></li> <li><a href="/contest/1342/standings">Положение</a></li> <li><a href="/contest/1342/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_edeb3d25b80955dbaf2ccbba46fdd2cd7839373d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ имеет период $$$k$$$, если $$$s_i = s_{i + k}$$$ для всех $$$i$$$ от $$$1$$$ по $$$|s| - k$$$ ($$$|s|$$$ — это длина строки $$$s$$$), и $$$k$$$ — минимальное положительное целое число с этим свойством.</p><p>Несколько примеров вычисления периода: для $$$s$$$=«<span class="tex-font-style-tt">0101</span>» период равен $$$k=2$$$, для $$$s$$$=«<span class="tex-font-style-tt">0000</span>» период равен $$$k=1$$$, для $$$s$$$=«<span class="tex-font-style-tt">010</span>» период равен $$$k=2$$$, для $$$s$$$=«<span class="tex-font-style-tt">0011</span>» период равен $$$k=4$$$. </p><p>Вам задана строка $$$t$$$, состоящая только из <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>, и вам нужно найти такую строку $$$s$$$, что:</p><ol> <li> Строка $$$s$$$ состоит только из <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>; </li><li> Длина $$$s$$$ не превосходит $$$2 \cdot |t|$$$; </li><li> Строка $$$t$$$ является подпоследовательностью строки $$$s$$$; </li><li> Строка $$$s$$$ имеет минимальный возможный период среди всех строк, удовлетворяющих условиям 1—3. </li></ol><p>Напомним, что $$$t$$$ является подпоследовательностью $$$s$$$, если $$$t$$$ можно получить из $$$s$$$ путем удаления нуля или более элементов (любых) и не меняя порядок оставшихся элементов. Например, $$$t$$$=«<span class="tex-font-style-tt">011</span>» — это подпоследовательность строки $$$s$$$=«<span class="tex-font-style-tt">10101</span>».</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество наборов входных данных.</p><p>В следующих $$$T$$$ строках заданы сами наборы — по одному на строку. В каждой строке задана строка $$$t$$$ ($$$1 \le |t| \le 100$$$), состоящая только из <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите по одной строке на каждый набор входных данных — строку $$$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 00 01 111 110 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00 01 11111 1010</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и втором наборе $$$s = t$$$, так как это уже одни из оптимальных решений. Периоды ответов равны $$$1$$$ и $$$2$$$, соответственно.</p><p>В третьем наборе, есть и другие более короткие ответы, но все в порядке, потому что не требуется минимизировать ответ $$$s$$$. Строка $$$s$$$ имеет период $$$1$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:02: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:'81249ebaaa1515f6',t:'MTY5NjY2NTcyNy4zMjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1100"]
1342C
1342
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.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два числа $$$a$$$ и $$$b$$$, а также $$$q$$$ запросов. $$$i$$$-й запрос состоит из двух чисел $$$l_i$$$ и $$$r_i$$$, и ответ на него — количество таких целых чисел $$$x$$$, что $$$l_i \le x \le r_i$$$ и $$$((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a)$$$. Вычислите ответ на каждый запрос.</p><p>Напоминаем, что $$$y \bmod z$$$ — остаток от деления $$$y$$$ на $$$z$$$. Например, $$$5 \bmod 3 = 2$$$, $$$7 \bmod 8 = 7$$$, $$$9 \bmod 4 = 1$$$, $$$9 \bmod 9 = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных. Затем следуют сами наборы.</p><p>Первая строка каждого набора содержит три целых числа $$$a$$$, $$$b$$$ и $$$q$$$ ($$$1 \le a, b \le 200$$$; $$$1 \le q \le 500$$$).</p><p>Затем следуют $$$q$$$ строк, каждая из которых содержит два числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^{18}$$$) для очередного запроса.</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> 2 4 6 5 1 1 1 3 1 5 1 7 1 9 7 10 2 7 8 100 200 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 2 4 0 91 </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="cfb9053aa809fdaacdaf8e683266d44e"/> <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="db4c5554a97fc92b10b3a4d69207641a29a444f5"/> <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='cfb9053aa809fdaacdaf8e683266d44e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1342%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='cfb9053aa809fdaacdaf8e683266d44e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1342">Educational Codeforces Round 86 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='cfb9053aa809fdaacdaf8e683266d44e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1342/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='cfb9053aa809fdaacdaf8e683266d44e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="604758"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cfb9053aa809fdaacdaf8e683266d44e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="604758"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76526" title="76526" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12608" resourceName="76526" resourceManual="true" src="//codeforces.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/76633" title="76633" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12607" resourceName="76633" resourceManual="true" src="//codeforces.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/1342">Задачи</a></li> <li><a href="/contest/1342/submit">Отослать</a></li> <li><a href="/contest/1342/my">Мои посылки</a></li> <li><a href="/contest/1342/status">Статус</a></li> <li><a href="/contest/1342/hacks">Взломы</a></li> <li><a href="/contest/1342/standings">Положение</a></li> <li><a href="/contest/1342/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1fc81cb400e4f48d08393afdc6a306c5a3032aa5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два числа $$$a$$$ и $$$b$$$, а также $$$q$$$ запросов. $$$i$$$-й запрос состоит из двух чисел $$$l_i$$$ и $$$r_i$$$, и ответ на него — количество таких целых чисел $$$x$$$, что $$$l_i \le x \le r_i$$$ и $$$((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a)$$$. Вычислите ответ на каждый запрос.</p><p>Напоминаем, что $$$y \bmod z$$$ — остаток от деления $$$y$$$ на $$$z$$$. Например, $$$5 \bmod 3 = 2$$$, $$$7 \bmod 8 = 7$$$, $$$9 \bmod 4 = 1$$$, $$$9 \bmod 9 = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных. Затем следуют сами наборы.</p><p>Первая строка каждого набора содержит три целых числа $$$a$$$, $$$b$$$ и $$$q$$$ ($$$1 \le a, b \le 200$$$; $$$1 \le q \le 500$$$).</p><p>Затем следуют $$$q$$$ строк, каждая из которых содержит два числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^{18}$$$) для очередного запроса.</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> 2 4 6 5 1 1 1 3 1 5 1 7 1 9 7 10 2 7 8 100 200 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 2 4 0 91 </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 11:02: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:'81249ec36e269d90',t:'MTY5NjY2NTcyOC43ODMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"]
1342D
1342
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>Итак, вы решили провести свой раунд на Codeforces. Приготовили задачи: условия, решения, чекеры, валидаторы, тесты... И тут внезапно ваш координатор просит вас заменить все ваши тесты в самой простой задачи на наборы входных данных!</p><p>Изначально каждый тест в данной задаче — это просто массив. Максимальный размер массива равен $$$k$$$. Для простоты будем считать, что содержимое массива не важно. У вас есть $$$n$$$ тестов; $$$i$$$-й тест — это массив размера $$$m_i$$$ ($$$1 \le m_i \le k$$$).</p><p>Ваш координатор просит вас распределить все ваши массивы по нескольким наборам входных данных. Каждый набор может включать в себя несколько массивов. Однако, в каждом наборе входных данных должно быть не больше $$$c_1$$$ массивов размера <span class="tex-font-style-bf">больше или равного $$$1$$$</span> ($$$\ge 1$$$), не больше $$$c_2$$$ массивов размера <span class="tex-font-style-bf">больше или равного $$$2$$$</span>, $$$\dots$$$, не больше $$$c_k$$$ массивов размера <span class="tex-font-style-bf">больше или равного $$$k$$$</span>. Также $$$c_1 \ge c_2 \ge \dots \ge c_k$$$.</p><p>Теперь ваша задача — составить новые наборы входных данных так, чтобы: </p><ul> <li> каждый из изначальных массивов встречается <span class="tex-font-style-bf">ровно в одном</span> наборе входных данных; </li><li> для каждого набора тестовых данных выполняются приведенные условия; </li><li> количество наборов тестовых данных минимально возможно. </li></ul><p>Выведите минимальное количество наборов тестовых данных, которое можно достичь, а также размеры массивов в каждом наборе входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 2 \cdot 10^5$$$) — изначальное количество тестов и ограничение на размер каждого массива.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$m_1, m_2, \dots, m_n$$$ ($$$1 \le m_i \le k$$$) — размеры массивов в изначальных тестах.</p><p>В третьей строке записаны $$$k$$$ целых чисел $$$c_1, c_2, \dots, c_k$$$ ($$$n \ge c_1 \ge c_2 \ge \dots \ge c_k \ge 1$$$); $$$c_i$$$ — это максимальное количество массивов размера больше или равного $$$i$$$, которые могут быть внутри одного набора входных данных.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число $$$ans$$$ ($$$1 \le ans \le n$$$) — минимальное количество наборов входных данных, которое можно достичь.</p><p>Каждая из следующих $$$ans$$$ строк должна содержать описание набора входных данных в следующем формате:</p><p>$$$t$$$ $$$a_1$$$ $$$a_2$$$ $$$\dots$$$ $$$a_{t}$$$ ($$$1 \le t\le n$$$) — в наборе входных данных содержится $$$t$$$ массивов, $$$a_i$$$ — это размер $$$i$$$-го массива в этом наборе входных данных.</p><p>Каждый из изначальных массивов должен содержаться в <span class="tex-font-style-bf">ровно одном</span> наборе входных данных. В частности, это подразумевает, что сумма всех значений $$$t$$$ по всем $$$ans$$$ наборам входных данных должна быть равна $$$n$$$.</p><p>Обратите внимание, что ответ существует всегда, потому что $$$c_k \ge 1$$$ (а следовательно $$$c_1 \ge 1$$$).</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 2 3 4 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 2 1 3 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 10 5 8 1 10 8 7 6 6 4 4 3 2 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 8 5 7 3 10 8 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 1 1 1 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 5 1 1 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 1 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 1 1 1 1 1 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере не существует способа распределить все тесты по меньше, чем $$$3$$$, наборам входных данных. Данный ответ удовлетворяет всем условиям: в каждом наборе входных данных не больше $$$4$$$ массивов размера больше или равного $$$1$$$ и не больше $$$1$$$ массива размера больше или равного $$$2$$$ и $$$3$$$.</p><p>Обратите внимание, что существует несколько правильных ответов на данный тест. Например, наборы входных данных с размерами $$$[[2], [1, 2], [3]]$$$ тоже будут правильными.</p><p>Однако, наборы тестовых данных с размерами $$$[[1, 2], [2, 3]]$$$ будут неправильными, потому что во втором наборе входных данных есть $$$2$$$ массива размера больше или равного $$$2$$$.</p><p>Обратите внимание на разницу между третьим и четвертым примером. В третьем примере можно собрать до $$$5$$$ массивов размера больше или равного $$$1$$$ в набор входных данных, поэтому одного набора достаточно. А в четвертом примере можно иметь не больше $$$1$$$ массива. Поэтому каждый массив приходится выделять в отдельный набор входных данных.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="9c8dd4f9376a42fe5509ca2fc71d6909"/> <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="db4c5554a97fc92b10b3a4d69207641a29a444f5"/> <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='9c8dd4f9376a42fe5509ca2fc71d6909'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1342%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='9c8dd4f9376a42fe5509ca2fc71d6909'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1342">Educational Codeforces Round 86 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='9c8dd4f9376a42fe5509ca2fc71d6909'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1342/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='9c8dd4f9376a42fe5509ca2fc71d6909'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="604759"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9c8dd4f9376a42fe5509ca2fc71d6909'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="604759"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76526" title="76526" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12608" resourceName="76526" resourceManual="true" src="//codeforces.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/76633" title="76633" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12607" resourceName="76633" resourceManual="true" src="//codeforces.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/1342">Задачи</a></li> <li><a href="/contest/1342/submit">Отослать</a></li> <li><a href="/contest/1342/my">Мои посылки</a></li> <li><a href="/contest/1342/status">Статус</a></li> <li><a href="/contest/1342/hacks">Взломы</a></li> <li><a href="/contest/1342/standings">Положение</a></li> <li><a href="/contest/1342/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_62a14e820aeb88865d5dfd94fae7b300c77102b9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Итак, вы решили провести свой раунд на Codeforces. Приготовили задачи: условия, решения, чекеры, валидаторы, тесты... И тут внезапно ваш координатор просит вас заменить все ваши тесты в самой простой задачи на наборы входных данных!</p><p>Изначально каждый тест в данной задаче — это просто массив. Максимальный размер массива равен $$$k$$$. Для простоты будем считать, что содержимое массива не важно. У вас есть $$$n$$$ тестов; $$$i$$$-й тест — это массив размера $$$m_i$$$ ($$$1 \le m_i \le k$$$).</p><p>Ваш координатор просит вас распределить все ваши массивы по нескольким наборам входных данных. Каждый набор может включать в себя несколько массивов. Однако, в каждом наборе входных данных должно быть не больше $$$c_1$$$ массивов размера <span class="tex-font-style-bf">больше или равного $$$1$$$</span> ($$$\ge 1$$$), не больше $$$c_2$$$ массивов размера <span class="tex-font-style-bf">больше или равного $$$2$$$</span>, $$$\dots$$$, не больше $$$c_k$$$ массивов размера <span class="tex-font-style-bf">больше или равного $$$k$$$</span>. Также $$$c_1 \ge c_2 \ge \dots \ge c_k$$$.</p><p>Теперь ваша задача — составить новые наборы входных данных так, чтобы: </p><ul> <li> каждый из изначальных массивов встречается <span class="tex-font-style-bf">ровно в одном</span> наборе входных данных; </li><li> для каждого набора тестовых данных выполняются приведенные условия; </li><li> количество наборов тестовых данных минимально возможно. </li></ul><p>Выведите минимальное количество наборов тестовых данных, которое можно достичь, а также размеры массивов в каждом наборе входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 2 \cdot 10^5$$$) — изначальное количество тестов и ограничение на размер каждого массива.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$m_1, m_2, \dots, m_n$$$ ($$$1 \le m_i \le k$$$) — размеры массивов в изначальных тестах.</p><p>В третьей строке записаны $$$k$$$ целых чисел $$$c_1, c_2, \dots, c_k$$$ ($$$n \ge c_1 \ge c_2 \ge \dots \ge c_k \ge 1$$$); $$$c_i$$$ — это максимальное количество массивов размера больше или равного $$$i$$$, которые могут быть внутри одного набора входных данных.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число $$$ans$$$ ($$$1 \le ans \le n$$$) — минимальное количество наборов входных данных, которое можно достичь.</p><p>Каждая из следующих $$$ans$$$ строк должна содержать описание набора входных данных в следующем формате:</p><p>$$$t$$$ $$$a_1$$$ $$$a_2$$$ $$$\dots$$$ $$$a_{t}$$$ ($$$1 \le t\le n$$$) — в наборе входных данных содержится $$$t$$$ массивов, $$$a_i$$$ — это размер $$$i$$$-го массива в этом наборе входных данных.</p><p>Каждый из изначальных массивов должен содержаться в <span class="tex-font-style-bf">ровно одном</span> наборе входных данных. В частности, это подразумевает, что сумма всех значений $$$t$$$ по всем $$$ans$$$ наборам входных данных должна быть равна $$$n$$$.</p><p>Обратите внимание, что ответ существует всегда, потому что $$$c_k \ge 1$$$ (а следовательно $$$c_1 \ge 1$$$).</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 2 3 4 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 2 1 3 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 10 5 8 1 10 8 7 6 6 4 4 3 2 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 8 5 7 3 10 8 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 1 1 1 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 5 1 1 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 1 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 1 1 1 1 1 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере не существует способа распределить все тесты по меньше, чем $$$3$$$, наборам входных данных. Данный ответ удовлетворяет всем условиям: в каждом наборе входных данных не больше $$$4$$$ массивов размера больше или равного $$$1$$$ и не больше $$$1$$$ массива размера больше или равного $$$2$$$ и $$$3$$$.</p><p>Обратите внимание, что существует несколько правильных ответов на данный тест. Например, наборы входных данных с размерами $$$[[2], [1, 2], [3]]$$$ тоже будут правильными.</p><p>Однако, наборы тестовых данных с размерами $$$[[1, 2], [2, 3]]$$$ будут неправильными, потому что во втором наборе входных данных есть $$$2$$$ массива размера больше или равного $$$2$$$.</p><p>Обратите внимание на разницу между третьим и четвертым примером. В третьем примере можно собрать до $$$5$$$ массивов размера больше или равного $$$1$$$ в набор входных данных, поэтому одного набора достаточно. А в четвертом примере можно иметь не больше $$$1$$$ массива. Поэтому каждый массив приходится выделять в отдельный набор входных данных.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'81249eccce9a16ab',t:'MTY5NjY2NTczMC4yNjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1900"]
1342E
1342
E
ru
E. Расстановка ладей
<div class="problem-statement"><div class="header"><div class="title">E. Расстановка ладей</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Посчитайте количество способов расставить $$$n$$$ ладей на доске $$$n \times n$$$ так, что выполняются оба следующих условия:</p><ul> <li> все пустые клетки атакованы; </li><li> ровно $$$k$$$ пар ладей атакуют друг друга. </li></ul><p>Пустая клетка считается атакованной, если хотя бы одна ладья находится в той же строке или в том же столбце. Две ладьи атакуют друг друга, если они находятся в одной и той же строке или в одном и том же столбце, <span class="tex-font-style-it">и между ними нет других ладей</span>. Например, на следующей картинке можно найти только две пары ладей, атакующих друг друга:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/39e963e792c25d833bed0b97bbe92cc970fe9f67.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Один из способов расставить ладьи при $$$n = 3$$$ и $$$k = 2$$$</span> </center><p>Два способа считаются различными, если существует хотя бы одна клетка, которая свободна в одном из способов и занята ладьей в другом способе.</p><p>Ответ может быть очень большим, поэтому выведите его по модулю $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 200000$$$; $$$0 \le k \le \frac{n(n - 1)}{2}$$$).</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 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1337 42 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 807905441 </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="8905fd0a2ae0c51f28edfc81646f4cd1"/> <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="db4c5554a97fc92b10b3a4d69207641a29a444f5"/> <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='8905fd0a2ae0c51f28edfc81646f4cd1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1342%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='8905fd0a2ae0c51f28edfc81646f4cd1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1342">Educational Codeforces Round 86 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='8905fd0a2ae0c51f28edfc81646f4cd1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1342/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье"> бпф </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='8905fd0a2ae0c51f28edfc81646f4cd1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="604760"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8905fd0a2ae0c51f28edfc81646f4cd1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="604760"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76526" title="76526" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12608" resourceName="76526" resourceManual="true" src="//codeforces.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/76633" title="76633" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12607" resourceName="76633" resourceManual="true" src="//codeforces.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/1342">Задачи</a></li> <li><a href="/contest/1342/submit">Отослать</a></li> <li><a href="/contest/1342/my">Мои посылки</a></li> <li><a href="/contest/1342/status">Статус</a></li> <li><a href="/contest/1342/hacks">Взломы</a></li> <li><a href="/contest/1342/standings">Положение</a></li> <li><a href="/contest/1342/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b0f69cac156fd6350f58ceb6a41e0555808be576"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Расстановка ладей</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Посчитайте количество способов расставить $$$n$$$ ладей на доске $$$n \times n$$$ так, что выполняются оба следующих условия:</p><ul> <li> все пустые клетки атакованы; </li><li> ровно $$$k$$$ пар ладей атакуют друг друга. </li></ul><p>Пустая клетка считается атакованной, если хотя бы одна ладья находится в той же строке или в том же столбце. Две ладьи атакуют друг друга, если они находятся в одной и той же строке или в одном и том же столбце, <span class="tex-font-style-it">и между ними нет других ладей</span>. Например, на следующей картинке можно найти только две пары ладей, атакующих друг друга:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/39e963e792c25d833bed0b97bbe92cc970fe9f67.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Один из способов расставить ладьи при $$$n = 3$$$ и $$$k = 2$$$</span> </center><p>Два способа считаются различными, если существует хотя бы одна клетка, которая свободна в одном из способов и занята ладьей в другом способе.</p><p>Ответ может быть очень большим, поэтому выведите его по модулю $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 200000$$$; $$$0 \le k \le \frac{n(n - 1)}{2}$$$).</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 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1337 42 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 807905441 </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 11:02: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:'81249ed5cc359d4c',t:'MTY5NjY2NTczMS42MTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2300"]
1342F
1342
F
ru
F. Сделай возрастающим
<div class="problem-statement"><div class="header"><div class="title">F. Сделай возрастающим</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дан массив $$$a$$$, состоящий из $$$n$$$ целых чисел. Вы можете применить несколько операций к этому массиву (возможно, ни одной).</p><p>Во время каждой операции вы выбираете два индекса $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$; $$$i \ne j$$$), увеличиваете $$$a_j$$$ на $$$a_i$$$, а затем удаляете $$$i$$$-й элемент из массива (при этом индексы всех элементов правее удаляемого уменьшаются на $$$1$$$, и размер массива $$$n$$$ также уменьшается на $$$1$$$).</p><p>Ваша цель — сделать массив $$$a$$$ строго возрастающим, то есть должно выполняться условие $$$a_1 &lt; a_2 &lt; \dots &lt; a_n$$$ (где $$$n$$$ — итоговый размер массива).</p><p>Посчитайте минимальное количество операций, которое требуется, чтобы массив стал возрастающим.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$T$$$ ($$$1 \le T \le 10000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из двух строк. Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 15$$$) — количество элементов в исходном массиве $$$a$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^6$$$).</p><p>Гарантируется, что: </p><ul> <li> количество наборов тестовых данных, в которых $$$n \ge 5$$$, не превосходит $$$5000$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 8$$$, не превосходит $$$500$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 10$$$, не превосходит $$$100$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 11$$$, не превосходит $$$50$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 12$$$, не превосходит $$$25$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 13$$$, не превосходит $$$10$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 14$$$, не превосходит $$$3$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 15$$$, не превосходит $$$1$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор тестовых данных выведите ответ следующим образом:</p><p>Сначала выведите $$$k$$$ — минимальное количество операций, которые вы должны сделать. Затем выведите $$$k$$$ строк, каждая из которых содержит два индекса $$$i$$$ и $$$j$$$ для соответствующей операции. Обратите внимание, что нумерация элементов меняется после удаления элемента из массива. Если существует несколько оптимальных последовательностей операций, выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных $$$a$$$ меняется следующим образом:</p><p>$$$[2, 1, 3, 5, 1, 2, 4, 5] \rightarrow [2, 1, 3, 5, 1, 4, 7] \rightarrow [1, 3, 5, 1, 6, 7] \rightarrow [2, 3, 5, 6, 7]$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="979d58bf525b92e066b4975bc8f56c80"/> <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="db4c5554a97fc92b10b3a4d69207641a29a444f5"/> <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='979d58bf525b92e066b4975bc8f56c80'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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%2F1342%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='979d58bf525b92e066b4975bc8f56c80'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1342">Educational Codeforces Round 86 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='979d58bf525b92e066b4975bc8f56c80'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1342/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='979d58bf525b92e066b4975bc8f56c80'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="604761"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='979d58bf525b92e066b4975bc8f56c80'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="604761"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76526" title="76526" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12608" resourceName="76526" resourceManual="true" src="//codeforces.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/76633" title="76633" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12607" resourceName="76633" resourceManual="true" src="//codeforces.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/1342">Задачи</a></li> <li><a href="/contest/1342/submit">Отослать</a></li> <li><a href="/contest/1342/my">Мои посылки</a></li> <li><a href="/contest/1342/status">Статус</a></li> <li><a href="/contest/1342/hacks">Взломы</a></li> <li><a href="/contest/1342/standings">Положение</a></li> <li><a href="/contest/1342/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_532261e92a7f107fcaa0d9ccd7befa5325a76cd5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Сделай возрастающим</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дан массив $$$a$$$, состоящий из $$$n$$$ целых чисел. Вы можете применить несколько операций к этому массиву (возможно, ни одной).</p><p>Во время каждой операции вы выбираете два индекса $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$; $$$i \ne j$$$), увеличиваете $$$a_j$$$ на $$$a_i$$$, а затем удаляете $$$i$$$-й элемент из массива (при этом индексы всех элементов правее удаляемого уменьшаются на $$$1$$$, и размер массива $$$n$$$ также уменьшается на $$$1$$$).</p><p>Ваша цель — сделать массив $$$a$$$ строго возрастающим, то есть должно выполняться условие $$$a_1 &lt; a_2 &lt; \dots &lt; a_n$$$ (где $$$n$$$ — итоговый размер массива).</p><p>Посчитайте минимальное количество операций, которое требуется, чтобы массив стал возрастающим.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$T$$$ ($$$1 \le T \le 10000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из двух строк. Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 15$$$) — количество элементов в исходном массиве $$$a$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^6$$$).</p><p>Гарантируется, что: </p><ul> <li> количество наборов тестовых данных, в которых $$$n \ge 5$$$, не превосходит $$$5000$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 8$$$, не превосходит $$$500$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 10$$$, не превосходит $$$100$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 11$$$, не превосходит $$$50$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 12$$$, не превосходит $$$25$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 13$$$, не превосходит $$$10$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 14$$$, не превосходит $$$3$$$; </li><li> количество наборов тестовых данных, в которых $$$n \ge 15$$$, не превосходит $$$1$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор тестовых данных выведите ответ следующим образом:</p><p>Сначала выведите $$$k$$$ — минимальное количество операций, которые вы должны сделать. Затем выведите $$$k$$$ строк, каждая из которых содержит два индекса $$$i$$$ и $$$j$$$ для соответствующей операции. Обратите внимание, что нумерация элементов меняется после удаления элемента из массива. Если существует несколько оптимальных последовательностей операций, выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 8 2 1 3 5 1 2 4 5 15 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 2 3 3 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 8 1 6 4 1 7 1 15 1 13 1 11 1 9 1 7 1 5 1 3 1 2 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных $$$a$$$ меняется следующим образом:</p><p>$$$[2, 1, 3, 5, 1, 2, 4, 5] \rightarrow [2, 1, 3, 5, 1, 4, 7] \rightarrow [1, 3, 5, 1, 6, 7] \rightarrow [2, 3, 5, 6, 7]$$$.</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 11:02: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:'81249ede4d0f1625',t:'MTY5NjY2NTczMi45NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*3000"]
1343A
1343
A
ru
A. Конфеты
<div class="problem-statement"><div class="header"><div class="title">A. Конфеты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Недавно Вова нашел $$$n$$$ фантиков от конфет. Он помнит, что он покупал $$$x$$$ конфет в первый день, $$$2x$$$ конфет во второй день, $$$4x$$$ конфет в третий день, $$$\dots$$$, $$$2^{k-1} x$$$ конфет в $$$k$$$-й день. Но есть проблема: Вова не помнит ни $$$x$$$, ни $$$k$$$, но он уверен, что $$$x$$$ и $$$k$$$ — положительные целые числа и $$$k &gt; 1$$$.</p><p>Вова будет удовлетворен, если вы назовете ему <span class="tex-font-style-bf">любое положительное</span> целое число $$$x$$$ такое, что существует целое число $$$k&gt;1$$$, при котором $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$. Гарантируется, что существует как минимум одно решение. <span class="tex-font-style-bf">Обратите внимание: $$$k &gt; 1$$$</span>.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$3 \le n \le 10^9$$$) — количество конфетных фантиков, которые нашел Вова. Гарантируется, что существуют некоторые положительные целые числа $$$x$$$ и $$$k&gt;1$$$ такие, что $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — <span class="tex-font-style-bf">любое положительное</span> целое значение $$$x$$$ такое, что существует целое число $$$k&gt;1$$$, при котором $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 6 7 21 28 999999999 999999984 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 7 4 333333333 333333328 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера одним из возможных ответов является $$$x=1, k=2$$$. Тогда $$$1 \cdot 1 + 2 \cdot 1$$$ равняется $$$n=3$$$.</p><p>Во втором наборе тестовых данных примера одним из возможных ответов является $$$x=2, k=2$$$. Тогда $$$1 \cdot 2 + 2 \cdot 2$$$ равняется $$$n=6$$$.</p><p>В третьем наборе тестовых данных примера одним из возможных ответов является $$$x=1, k=3$$$. Тогда $$$1 \cdot 1 + 2 \cdot 1 + 4 \cdot 1$$$ равняется $$$n=7$$$.</p><p>В четвертом наборе тестовых данных примера одним из возможных ответов является $$$x=7, k=2$$$. Тогда $$$1 \cdot 7 + 2 \cdot 7$$$ равняется $$$n=21$$$.</p><p>В пятом наборе тестовых данных примера одним из возможных ответов является $$$x=4, k=3$$$. Тогда $$$1 \cdot 4 + 2 \cdot 4 + 4 \cdot 4$$$ равняется $$$n=28$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a89000b8ad4afc39304493cdc7d1a98e"/> <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="6bb175fa17c6403280044c1a13f9a5461e452ba9"/> <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='a89000b8ad4afc39304493cdc7d1a98e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1343%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='a89000b8ad4afc39304493cdc7d1a98e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1343">Codeforces Round 636 (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='a89000b8ad4afc39304493cdc7d1a98e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1343/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='a89000b8ad4afc39304493cdc7d1a98e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599887"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a89000b8ad4afc39304493cdc7d1a98e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599887"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76306" title="Codeforces Round #636 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10786:10787" 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/76352" title="76352" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10793:10794" 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/1343">Задачи</a></li> <li><a href="/contest/1343/submit">Отослать</a></li> <li><a href="/contest/1343/my">Мои посылки</a></li> <li><a href="/contest/1343/status">Статус</a></li> <li><a href="/contest/1343/hacks">Взломы</a></li> <li><a href="/contest/1343/standings">Положение</a></li> <li><a href="/contest/1343/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2f64f9de8bf963e1dd6adc4acb3da5dae6bd992d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Конфеты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Недавно Вова нашел $$$n$$$ фантиков от конфет. Он помнит, что он покупал $$$x$$$ конфет в первый день, $$$2x$$$ конфет во второй день, $$$4x$$$ конфет в третий день, $$$\dots$$$, $$$2^{k-1} x$$$ конфет в $$$k$$$-й день. Но есть проблема: Вова не помнит ни $$$x$$$, ни $$$k$$$, но он уверен, что $$$x$$$ и $$$k$$$ — положительные целые числа и $$$k &gt; 1$$$.</p><p>Вова будет удовлетворен, если вы назовете ему <span class="tex-font-style-bf">любое положительное</span> целое число $$$x$$$ такое, что существует целое число $$$k&gt;1$$$, при котором $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$. Гарантируется, что существует как минимум одно решение. <span class="tex-font-style-bf">Обратите внимание: $$$k &gt; 1$$$</span>.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$3 \le n \le 10^9$$$) — количество конфетных фантиков, которые нашел Вова. Гарантируется, что существуют некоторые положительные целые числа $$$x$$$ и $$$k&gt;1$$$ такие, что $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — <span class="tex-font-style-bf">любое положительное</span> целое значение $$$x$$$ такое, что существует целое число $$$k&gt;1$$$, при котором $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 6 7 21 28 999999999 999999984 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 7 4 333333333 333333328 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера одним из возможных ответов является $$$x=1, k=2$$$. Тогда $$$1 \cdot 1 + 2 \cdot 1$$$ равняется $$$n=3$$$.</p><p>Во втором наборе тестовых данных примера одним из возможных ответов является $$$x=2, k=2$$$. Тогда $$$1 \cdot 2 + 2 \cdot 2$$$ равняется $$$n=6$$$.</p><p>В третьем наборе тестовых данных примера одним из возможных ответов является $$$x=1, k=3$$$. Тогда $$$1 \cdot 1 + 2 \cdot 1 + 4 \cdot 1$$$ равняется $$$n=7$$$.</p><p>В четвертом наборе тестовых данных примера одним из возможных ответов является $$$x=7, k=2$$$. Тогда $$$1 \cdot 7 + 2 \cdot 7$$$ равняется $$$n=21$$$.</p><p>В пятом наборе тестовых данных примера одним из возможных ответов является $$$x=4, k=3$$$. Тогда $$$1 \cdot 4 + 2 \cdot 4 + 4 \cdot 4$$$ равняется $$$n=28$$$.</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 11:02: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:'81249ee69a6a0065',t:'MTY5NjY2NTczNC4zNzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*900"]
1343B
1343
B
ru
B. Сбалансированный массив
<div class="problem-statement"><div class="header"><div class="title">B. Сбалансированный массив</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано положительное целое число $$$n$$$, гарантируется, что $$$n$$$ четное (то есть делится на $$$2$$$).</p><p>Вы хотите построить такой массив $$$a$$$ длины $$$n$$$, что: </p><ul> <li> Первые $$$\frac{n}{2}$$$ элементов $$$a$$$ четные (делятся на $$$2$$$); </li><li> вторые $$$\frac{n}{2}$$$ элементов $$$a$$$ нечетные (не делятся на $$$2$$$); </li><li> <span class="tex-font-style-bf">все элементы в $$$a$$$ различны и положительны</span>; </li><li> сумма элементов первой половины равна сумме элементов второй половины ($$$\sum\limits_{i=1}^{\frac{n}{2}} a_i = \sum\limits_{i=\frac{n}{2} + 1}^{n} a_i$$$). </li></ul><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 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — длину массива. Гарантируется, что $$$n$$$ четное (то есть делится на $$$2$$$).</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — «<span class="tex-font-style-tt">NO</span>» (без кавычек), если не существует подходящего ответа для заданного набора, или «<span class="tex-font-style-tt">YES</span>» первой строкой и <span class="tex-font-style-bf">любой</span> подходящий массив $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), удовлетворяющий условиям из условия задачи, второй строкой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 4 6 8 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO YES 2 4 1 5 NO YES 2 4 6 8 1 3 5 11 NO </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b8a2b5920dadfd7eded35bb3af2f429c"/> <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="6bb175fa17c6403280044c1a13f9a5461e452ba9"/> <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='b8a2b5920dadfd7eded35bb3af2f429c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1343%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='b8a2b5920dadfd7eded35bb3af2f429c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1343">Codeforces Round 636 (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='b8a2b5920dadfd7eded35bb3af2f429c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1343/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='b8a2b5920dadfd7eded35bb3af2f429c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599888"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b8a2b5920dadfd7eded35bb3af2f429c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599888"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76306" title="Codeforces Round #636 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10786:10787" 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/76352" title="76352" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10793:10794" 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/1343">Задачи</a></li> <li><a href="/contest/1343/submit">Отослать</a></li> <li><a href="/contest/1343/my">Мои посылки</a></li> <li><a href="/contest/1343/status">Статус</a></li> <li><a href="/contest/1343/hacks">Взломы</a></li> <li><a href="/contest/1343/standings">Положение</a></li> <li><a href="/contest/1343/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_702b3fa8b8535f0c386a439b5bbb57a71bf49db4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Сбалансированный массив</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано положительное целое число $$$n$$$, гарантируется, что $$$n$$$ четное (то есть делится на $$$2$$$).</p><p>Вы хотите построить такой массив $$$a$$$ длины $$$n$$$, что: </p><ul> <li> Первые $$$\frac{n}{2}$$$ элементов $$$a$$$ четные (делятся на $$$2$$$); </li><li> вторые $$$\frac{n}{2}$$$ элементов $$$a$$$ нечетные (не делятся на $$$2$$$); </li><li> <span class="tex-font-style-bf">все элементы в $$$a$$$ различны и положительны</span>; </li><li> сумма элементов первой половины равна сумме элементов второй половины ($$$\sum\limits_{i=1}^{\frac{n}{2}} a_i = \sum\limits_{i=\frac{n}{2} + 1}^{n} a_i$$$). </li></ul><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 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — длину массива. Гарантируется, что $$$n$$$ четное (то есть делится на $$$2$$$).</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — «<span class="tex-font-style-tt">NO</span>» (без кавычек), если не существует подходящего ответа для заданного набора, или «<span class="tex-font-style-tt">YES</span>» первой строкой и <span class="tex-font-style-bf">любой</span> подходящий массив $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), удовлетворяющий условиям из условия задачи, второй строкой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 4 6 8 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO YES 2 4 1 5 NO YES 2 4 6 8 1 3 5 11 NO </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 11:02: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:'81249eef9a189d92',t:'MTY5NjY2NTczNS42OTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"]
1343C
1343
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>Напомним, что последовательность $$$b$$$ является подпоследовательностью последовательности $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ путем удаления нуля или более элементов без изменения порядка оставшихся элементов. Например, если $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, то возможные подпоследовательности: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ и $$$[1, 2, 1, 3, 1, 2, 1]$$$, но не $$$[3, 2, 3]$$$ и $$$[1, 1, 1, 1, 2]$$$.</p><p>Вам задана последовательность $$$a$$$, состоящая из $$$n$$$ положительных и отрицательных элементов (в последовательности нет нулей).</p><p>Ваша задача выбрать <span class="tex-font-style-bf">максимальную по размеру</span> (длине) <span class="tex-font-style-it">чередующуюся</span> подпоследовательность заданной последовательности (то есть знак каждого следующего элемента противоположен знаку текущего элемента, например, положительный-отрицательный-положительный и так далее или отрицательный-положительный-отрицательный и так далее). Из всех таких подпоследовательностей вам нужно выбрать ту, которая имеет <span class="tex-font-style-bf">максимальную сумму</span> элементов.</p><p>Другими словами, если максимальная длина <span class="tex-font-style-it">чередующейся</span> подпоследовательности равна $$$k$$$, то ваша задача — найти <span class="tex-font-style-bf">максимальную сумму</span> элементов какой-то <span class="tex-font-style-it">чередующейся</span> подпоследовательности длины $$$k$$$.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество элементов в $$$a$$$. Вторая строка набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), где $$$a_i$$$ — $$$i$$$-й элемент в $$$a$$$.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — <span class="tex-font-style-bf">максимальную сумму</span> <span class="tex-font-style-bf">максимальной по размеру</span> (длине) <span class="tex-font-style-it">чередующейся</span> подпоследовательности $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 2 3 -1 -2 4 -1 -2 -1 -3 10 -2 8 3 8 -4 -15 5 -2 -3 1 6 1 -1000000000 1 -1000000000 1 -1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 -1 6 -2999999997 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера одним из возможных ответов является $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.</p><p>Во втором наборе тестовых данных примера одним из возможных ответов является $$$[-1, -2, \underline{-1}, -3]$$$.</p><p>В третьем наборе тестовых данных примера одним из возможных ответов является $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.</p><p>В четвертом наборе тестовых данных примера одним из возможных ответов является $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4ba0d2b407edfdb92ed5dd9aa3502fdb"/> <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="6bb175fa17c6403280044c1a13f9a5461e452ba9"/> <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='4ba0d2b407edfdb92ed5dd9aa3502fdb'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1343%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='4ba0d2b407edfdb92ed5dd9aa3502fdb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1343">Codeforces Round 636 (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='4ba0d2b407edfdb92ed5dd9aa3502fdb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1343/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='4ba0d2b407edfdb92ed5dd9aa3502fdb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599889"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4ba0d2b407edfdb92ed5dd9aa3502fdb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599889"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76306" title="Codeforces Round #636 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10786:10787" 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/76352" title="76352" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10793:10794" 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/1343">Задачи</a></li> <li><a href="/contest/1343/submit">Отослать</a></li> <li><a href="/contest/1343/my">Мои посылки</a></li> <li><a href="/contest/1343/status">Статус</a></li> <li><a href="/contest/1343/hacks">Взломы</a></li> <li><a href="/contest/1343/standings">Положение</a></li> <li><a href="/contest/1343/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0e88b2fd53b4ba22166f2ef8c24a356672b81847"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Напомним, что последовательность $$$b$$$ является подпоследовательностью последовательности $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ путем удаления нуля или более элементов без изменения порядка оставшихся элементов. Например, если $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, то возможные подпоследовательности: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ и $$$[1, 2, 1, 3, 1, 2, 1]$$$, но не $$$[3, 2, 3]$$$ и $$$[1, 1, 1, 1, 2]$$$.</p><p>Вам задана последовательность $$$a$$$, состоящая из $$$n$$$ положительных и отрицательных элементов (в последовательности нет нулей).</p><p>Ваша задача выбрать <span class="tex-font-style-bf">максимальную по размеру</span> (длине) <span class="tex-font-style-it">чередующуюся</span> подпоследовательность заданной последовательности (то есть знак каждого следующего элемента противоположен знаку текущего элемента, например, положительный-отрицательный-положительный и так далее или отрицательный-положительный-отрицательный и так далее). Из всех таких подпоследовательностей вам нужно выбрать ту, которая имеет <span class="tex-font-style-bf">максимальную сумму</span> элементов.</p><p>Другими словами, если максимальная длина <span class="tex-font-style-it">чередующейся</span> подпоследовательности равна $$$k$$$, то ваша задача — найти <span class="tex-font-style-bf">максимальную сумму</span> элементов какой-то <span class="tex-font-style-it">чередующейся</span> подпоследовательности длины $$$k$$$.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество элементов в $$$a$$$. Вторая строка набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), где $$$a_i$$$ — $$$i$$$-й элемент в $$$a$$$.</p><p>Гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — <span class="tex-font-style-bf">максимальную сумму</span> <span class="tex-font-style-bf">максимальной по размеру</span> (длине) <span class="tex-font-style-it">чередующейся</span> подпоследовательности $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 2 3 -1 -2 4 -1 -2 -1 -3 10 -2 8 3 8 -4 -15 5 -2 -3 1 6 1 -1000000000 1 -1000000000 1 -1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 -1 6 -2999999997 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера одним из возможных ответов является $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.</p><p>Во втором наборе тестовых данных примера одним из возможных ответов является $$$[-1, -2, \underline{-1}, -3]$$$.</p><p>В третьем наборе тестовых данных примера одним из возможных ответов является $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.</p><p>В четвертом наборе тестовых данных примера одним из возможных ответов является $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$.</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 11:02: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:'81249ef7cb681683',t:'MTY5NjY2NTczNy4wMTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1200"]
1343D
1343
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>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел (гарантируется, что $$$n$$$ четное, то есть делится на $$$2$$$). Все $$$a_i$$$ не превосходят некоторое число $$$k$$$.</p><p>Ваша задача — заменить <span class="tex-font-style-bf">минимальное</span> количество элементов (под заменой понимается следующая операция: выбрать некоторый индекс $$$i$$$ от $$$1$$$ до $$$n$$$ и заменить $$$a_i$$$ на некоторое целое число в отрезке $$$[1; k]$$$) так, чтобы удовлетворялись следующие условия:</p><ul> <li> после всех замен все $$$a_i$$$ — положительные целые числа, не превосходящие $$$k$$$; </li><li> для всех $$$i$$$ от $$$1$$$ до $$$\frac{n}{2}$$$ верно следующее равенство: $$$a_i + a_{n - i + 1} = x$$$, где $$$x$$$ должен быть <span class="tex-font-style-bf">одинаковым</span> для всех $$$\frac{n}{2}$$$ пар элементов. </li></ul><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le k \le 2 \cdot 10^5$$$) — длину $$$a$$$ и максимально возможное значение $$$a_i$$$ соответственно. Гарантируется, что $$$n$$$ четное (то есть делится на $$$2$$$). Вторая строка набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — $$$i$$$-й элемент в $$$a$$$.</p><p>Гарантируется, что сумма чисел $$$n$$$ (так же, как и сумма чисел $$$k$$$) по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum k \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите в ответ на него — <span class="tex-font-style-bf">минимальное</span> количество элементов, которое нужно заменить в $$$a$$$, чтобы удовлетворить все условия задачи.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 2 1 2 1 2 4 3 1 2 2 1 8 7 6 1 1 7 6 3 4 6 6 6 5 2 6 1 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 4 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="e4bd4e7b43ac753755911eddd8827889"/> <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="6bb175fa17c6403280044c1a13f9a5461e452ba9"/> <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='e4bd4e7b43ac753755911eddd8827889'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1343%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='e4bd4e7b43ac753755911eddd8827889'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1343">Codeforces Round 636 (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='e4bd4e7b43ac753755911eddd8827889'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1343/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='e4bd4e7b43ac753755911eddd8827889'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599890"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e4bd4e7b43ac753755911eddd8827889'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599890"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76306" title="Codeforces Round #636 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10786:10787" 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/76352" title="76352" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10793:10794" 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/1343">Задачи</a></li> <li><a href="/contest/1343/submit">Отослать</a></li> <li><a href="/contest/1343/my">Мои посылки</a></li> <li><a href="/contest/1343/status">Статус</a></li> <li><a href="/contest/1343/hacks">Взломы</a></li> <li><a href="/contest/1343/standings">Положение</a></li> <li><a href="/contest/1343/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_58c4a67f9d278eb6c5f904c928e478eeb3f4f45c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел (гарантируется, что $$$n$$$ четное, то есть делится на $$$2$$$). Все $$$a_i$$$ не превосходят некоторое число $$$k$$$.</p><p>Ваша задача — заменить <span class="tex-font-style-bf">минимальное</span> количество элементов (под заменой понимается следующая операция: выбрать некоторый индекс $$$i$$$ от $$$1$$$ до $$$n$$$ и заменить $$$a_i$$$ на некоторое целое число в отрезке $$$[1; k]$$$) так, чтобы удовлетворялись следующие условия:</p><ul> <li> после всех замен все $$$a_i$$$ — положительные целые числа, не превосходящие $$$k$$$; </li><li> для всех $$$i$$$ от $$$1$$$ до $$$\frac{n}{2}$$$ верно следующее равенство: $$$a_i + a_{n - i + 1} = x$$$, где $$$x$$$ должен быть <span class="tex-font-style-bf">одинаковым</span> для всех $$$\frac{n}{2}$$$ пар элементов. </li></ul><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le k \le 2 \cdot 10^5$$$) — длину $$$a$$$ и максимально возможное значение $$$a_i$$$ соответственно. Гарантируется, что $$$n$$$ четное (то есть делится на $$$2$$$). Вторая строка набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — $$$i$$$-й элемент в $$$a$$$.</p><p>Гарантируется, что сумма чисел $$$n$$$ (так же, как и сумма чисел $$$k$$$) по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum k \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите в ответ на него — <span class="tex-font-style-bf">минимальное</span> количество элементов, которое нужно заменить в $$$a$$$, чтобы удовлетворить все условия задачи.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 2 1 2 1 2 4 3 1 2 2 1 8 7 6 1 1 7 6 3 4 6 6 6 5 2 6 1 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 4 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 11:02: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:'81249efffe0d16f7',t:'MTY5NjY2NTczOC4zNTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1700"]
1343E
1343
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$$$ вершин и $$$m$$$ ребер (который представляет карту Бертауна), а также массив цен $$$p$$$ длины $$$m$$$. Гарантируется, что между каждой парой вершин (районов) существует путь.</p><p>Майк планирует совершить путешествие из вершины (района) $$$a$$$ в вершину (район) $$$b$$$, а затем из вершины (района) $$$b$$$ в вершину (район) $$$c$$$. Он может посещать один и тот же район дважды или даже большее число раз. Но есть небольшая проблема: власти города хотят ввести цену за использование дорог, таким образом, что если кто-то проходит по ней, то он должен заплатить цену, соответствующую этой дороге (<span class="tex-font-style-bf">он платит каждый раз, когда проходит по дороге</span>). Список используемых цен $$$p$$$ готов и они просто хотят распределить его между всеми дорогами в городе таким образом, что каждая цена из массива соответствует ровно одной дороге.</p><p>Вы являетесь хорошим другом Майка (и, внезапно, мэром Бертауна) и хотите помочь сделать его путешествие настолько дешевым, насколько это возможно. Таким образом, ваша задача заключается в том, чтобы распределить цены между дорогами таким образом, что если Майк выберет оптимальный путь, то цена его путешествия будет <span class="tex-font-style-bf">минимально</span> возможной. <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 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит пять целых чисел $$$n, m, a, b$$$ и $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — количество вершин, количество ребер и районы в путешествии Майка.</p><p>Вторая строка набора тестовых данных содержит $$$m$$$ целых чисел $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), где $$$p_i$$$ равно $$$i$$$-й цене из массива.</p><p>Следующие $$$m$$$ строк набора тестовых данных описывают ребра: ребро $$$i$$$ предствалено парой целых чисел $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), которые означают индексы вершин, соединенных ребром. Гарантируется, что в графе не существует петель и кратных ребер, то есть для каждой пары ($$$v_i, u_i$$$) в списке ребер не существует других пар ($$$v_i, u_i$$$) или ($$$u_i, v_i$$$), а также для каждой пары $$$(v_i, u_i)$$$ выполняется условие $$$v_i \ne u_i$$$. Гарантируется, что заданный граф является связным.</p><p>Гарантируется, что сумма $$$n$$$ (также как и сумма $$$m$$$) не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на каждый набор тестовых данных — <span class="tex-font-style-bf">минимально</span> возможную цену путешествия Майка, если вы распределите цены между ребрами оптимально.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 12 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Одно из возможных решение первого набора тестовых данных из примера:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/bcd57e84c44bc22ccce7e5005c98f3f1d0fadebf.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Одно из возможных решение второго набора тестовых данных из примера:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/f1d0f51cf563c458a58154af19f523d4cb7bafc0.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="08385ecbf7900f55c8466ad75415ab8d"/> <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="6bb175fa17c6403280044c1a13f9a5461e452ba9"/> <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='08385ecbf7900f55c8466ad75415ab8d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1343%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='08385ecbf7900f55c8466ad75415ab8d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1343">Codeforces Round 636 (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='08385ecbf7900f55c8466ad75415ab8d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1343/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='08385ecbf7900f55c8466ad75415ab8d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599892"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='08385ecbf7900f55c8466ad75415ab8d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599892"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76306" title="Codeforces Round #636 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10786:10787" 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/76352" title="76352" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10793:10794" 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/1343">Задачи</a></li> <li><a href="/contest/1343/submit">Отослать</a></li> <li><a href="/contest/1343/my">Мои посылки</a></li> <li><a href="/contest/1343/status">Статус</a></li> <li><a href="/contest/1343/hacks">Взломы</a></li> <li><a href="/contest/1343/standings">Положение</a></li> <li><a href="/contest/1343/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b5bbe3168a7fbfb845b5abc2eda491ecd435b9e9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ вершин и $$$m$$$ ребер (который представляет карту Бертауна), а также массив цен $$$p$$$ длины $$$m$$$. Гарантируется, что между каждой парой вершин (районов) существует путь.</p><p>Майк планирует совершить путешествие из вершины (района) $$$a$$$ в вершину (район) $$$b$$$, а затем из вершины (района) $$$b$$$ в вершину (район) $$$c$$$. Он может посещать один и тот же район дважды или даже большее число раз. Но есть небольшая проблема: власти города хотят ввести цену за использование дорог, таким образом, что если кто-то проходит по ней, то он должен заплатить цену, соответствующую этой дороге (<span class="tex-font-style-bf">он платит каждый раз, когда проходит по дороге</span>). Список используемых цен $$$p$$$ готов и они просто хотят распределить его между всеми дорогами в городе таким образом, что каждая цена из массива соответствует ровно одной дороге.</p><p>Вы являетесь хорошим другом Майка (и, внезапно, мэром Бертауна) и хотите помочь сделать его путешествие настолько дешевым, насколько это возможно. Таким образом, ваша задача заключается в том, чтобы распределить цены между дорогами таким образом, что если Майк выберет оптимальный путь, то цена его путешествия будет <span class="tex-font-style-bf">минимально</span> возможной. <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 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит пять целых чисел $$$n, m, a, b$$$ и $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — количество вершин, количество ребер и районы в путешествии Майка.</p><p>Вторая строка набора тестовых данных содержит $$$m$$$ целых чисел $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), где $$$p_i$$$ равно $$$i$$$-й цене из массива.</p><p>Следующие $$$m$$$ строк набора тестовых данных описывают ребра: ребро $$$i$$$ предствалено парой целых чисел $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), которые означают индексы вершин, соединенных ребром. Гарантируется, что в графе не существует петель и кратных ребер, то есть для каждой пары ($$$v_i, u_i$$$) в списке ребер не существует других пар ($$$v_i, u_i$$$) или ($$$u_i, v_i$$$), а также для каждой пары $$$(v_i, u_i)$$$ выполняется условие $$$v_i \ne u_i$$$. Гарантируется, что заданный граф является связным.</p><p>Гарантируется, что сумма $$$n$$$ (также как и сумма $$$m$$$) не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на каждый набор тестовых данных — <span class="tex-font-style-bf">минимально</span> возможную цену путешествия Майка, если вы распределите цены между ребрами оптимально.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 12 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Одно из возможных решение первого набора тестовых данных из примера:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/bcd57e84c44bc22ccce7e5005c98f3f1d0fadebf.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Одно из возможных решение второго набора тестовых данных из примера:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/f1d0f51cf563c458a58154af19f523d4cb7bafc0.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'81249f0879ac3a89',t:'MTY5NjY2NTczOS44NTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2100"]
1343F
1343
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$$$, состоящую из $$$n$$$ целых чисел. Перестановкой длины $$$n$$$ называется массив длины $$$n$$$, где каждый элемент от $$$1$$$ до $$$n$$$ встречается ровно один раз. Эта перестановка вам неизвестна.</p><p>Для каждой позиции $$$r$$$ от $$$2$$$ до $$$n$$$ мы выбрали некоторый другой индекс $$$l$$$ ($$$l &lt; r$$$) и дали вам отрезок $$$p_l, p_{l + 1}, \dots, p_r$$$ в <span class="tex-font-style-bf">отсортированном</span> порядке (то есть мы переставили элементы на этом отрезке так, что элементы на этом отрезке оказались отсортированными). Таким образом, вам задан ровно $$$n-1$$$ отрезок первоначальной перестановки, но элементы внутри каждого отрезка отсортированы. Отрезки даны вам в случайном порядке.</p><p>Например, если загаданная перестановка — $$$p=[3, 1, 4, 6, 2, 5]$$$, то возможное заданное множество отрезков:</p><ul> <li> $$$[2, 5, 6]$$$ </li><li> $$$[4, 6]$$$ </li><li> $$$[1, 3, 4]$$$ </li><li> $$$[1, 3]$$$ </li><li> $$$[1, 2, 4, 6]$$$ </li></ul><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 100$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 200$$$) — длину перестановки.</p><p>Следующая $$$n-1$$$ строка описывает заданные отрезки.</p><p>$$$i$$$-я строка содержит описание $$$i$$$-го отрезка. Строка начинается с числа $$$k_i$$$ ($$$2 \le k_i \le n$$$) — длины $$$i$$$-го отрезка. Затем следуют $$$k_i$$$ целых чисел. Все числа в строке различны, отсортированы по возрастанию, между $$$1$$$ и $$$n$$$, включительно.</p><p>Гарантируется, что искомая перестановка $$$p$$$ существует для каждого набора тестовых данных.</p><p>Также гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$200$$$ ($$$\sum n \le 200$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ: $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, все $$$p_i$$$ должны быть различны) — <span class="tex-font-style-bf">любую</span> подходящую перестановку (то есть любую перестановку, удовлетворяющую входным данным набора тестовых данных).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 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="c3fad75d2e2a634af7d3deca1c675055"/> <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="6bb175fa17c6403280044c1a13f9a5461e452ba9"/> <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='c3fad75d2e2a634af7d3deca1c675055'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1343%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='c3fad75d2e2a634af7d3deca1c675055'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1343">Codeforces Round 636 (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='c3fad75d2e2a634af7d3deca1c675055'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1343/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='c3fad75d2e2a634af7d3deca1c675055'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="599891"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c3fad75d2e2a634af7d3deca1c675055'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="599891"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76306" title="Codeforces Round #636 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10786:10787" 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/76352" title="76352" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10793:10794" 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/1343">Задачи</a></li> <li><a href="/contest/1343/submit">Отослать</a></li> <li><a href="/contest/1343/my">Мои посылки</a></li> <li><a href="/contest/1343/status">Статус</a></li> <li><a href="/contest/1343/hacks">Взломы</a></li> <li><a href="/contest/1343/standings">Положение</a></li> <li><a href="/contest/1343/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_19696b3ee4706cd761a9db597a9682ad18bfdd16"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$, состоящую из $$$n$$$ целых чисел. Перестановкой длины $$$n$$$ называется массив длины $$$n$$$, где каждый элемент от $$$1$$$ до $$$n$$$ встречается ровно один раз. Эта перестановка вам неизвестна.</p><p>Для каждой позиции $$$r$$$ от $$$2$$$ до $$$n$$$ мы выбрали некоторый другой индекс $$$l$$$ ($$$l &lt; r$$$) и дали вам отрезок $$$p_l, p_{l + 1}, \dots, p_r$$$ в <span class="tex-font-style-bf">отсортированном</span> порядке (то есть мы переставили элементы на этом отрезке так, что элементы на этом отрезке оказались отсортированными). Таким образом, вам задан ровно $$$n-1$$$ отрезок первоначальной перестановки, но элементы внутри каждого отрезка отсортированы. Отрезки даны вам в случайном порядке.</p><p>Например, если загаданная перестановка — $$$p=[3, 1, 4, 6, 2, 5]$$$, то возможное заданное множество отрезков:</p><ul> <li> $$$[2, 5, 6]$$$ </li><li> $$$[4, 6]$$$ </li><li> $$$[1, 3, 4]$$$ </li><li> $$$[1, 3]$$$ </li><li> $$$[1, 2, 4, 6]$$$ </li></ul><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 100$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 200$$$) — длину перестановки.</p><p>Следующая $$$n-1$$$ строка описывает заданные отрезки.</p><p>$$$i$$$-я строка содержит описание $$$i$$$-го отрезка. Строка начинается с числа $$$k_i$$$ ($$$2 \le k_i \le n$$$) — длины $$$i$$$-го отрезка. Затем следуют $$$k_i$$$ целых чисел. Все числа в строке различны, отсортированы по возрастанию, между $$$1$$$ и $$$n$$$, включительно.</p><p>Гарантируется, что искомая перестановка $$$p$$$ существует для каждого набора тестовых данных.</p><p>Также гарантируется, что сумма чисел $$$n$$$ по всем наборам тестовых данных не превосходит $$$200$$$ ($$$\sum n \le 200$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ: $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, все $$$p_i$$$ должны быть различны) — <span class="tex-font-style-bf">любую</span> подходящую перестановку (то есть любую перестановку, удовлетворяющую входным данным набора тестовых данных).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 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 11:02: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:'81249f11beca9d3a',t:'MTY5NjY2NTc0My41NzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\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", "\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"]
1344A
1344
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-bf">включая ноль и отрицательные числа</span>. Не менее странно то, что сейчас отель полностью заполнен, что означает, что в каждой комнате находится ровно один гость. Менеджер отеля, сам Давид Гильберт, решил переместить гостей, потому что у него есть предположение, что за счет этого образуются свободные места.</p><p>Для любого целого числа $$$k$$$ и положительного целого числа $$$n$$$ обозначим за $$$k\bmod n$$$ остаток при делении числа $$$k$$$ на число $$$n$$$. Более формально, $$$r=k\bmod n$$$ это наименьшее неотрицательное целое число такое, что $$$k-r$$$ делится на $$$n$$$. Всегда выполнено, что $$$0\le k\bmod n\le n-1$$$. Например, $$$100\bmod 12=4$$$ и $$$(-1337)\bmod 3=1$$$.</p><p>Процесс перемещения гостей выглядит следующим образом: есть массив, состоящий из $$$n$$$ целых чисел $$$a_0,a_1,\ldots,a_{n-1}$$$. Тогда для всех целых чисел $$$k$$$ гость из комнаты с номером $$$k$$$ перемещается в комнату с номером $$$k+a_{k\bmod n}$$$.</p><p>Определите, верно ли, что после этого процесса перемещения в каждой комнате по-прежнему находится ровно один гость. Это означает, что нет пустых комнат и комнат, в которых больше одного гостя.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких тестовых случаев. Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество тестовых случаев. Следующие $$$2t$$$ строк содержат описания тестовых случаев.</p><p>В первой строке описания каждого тестового случая находится единственное целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — длина массива.</p><p>Во второй строке описания каждого тестового случая находятся $$$n$$$ целых чисел $$$a_0,a_1,\ldots,a_{n-1}$$$ ($$$-10^9\le a_i\le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите единственную строку, содержащую «<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 1 14 2 1 -1 4 5 5 5 1 3 3 2 1 2 0 1 5 -239 -2 -100 -3 -11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES NO NO YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае номер комнаты каждого гостя увеличился на $$$14$$$, поэтому по-прежнему в каждой комнате находится ровно один гость.</p><p>Во втором тестовом случае гости в комнатах с четными номерами перемещаются в комнату с номером, на $$$1$$$ большим исходного; гости в комнатах с нечетными номерами перемещаются в комнату с номером, на $$$1$$$ меньшим исходного. Можно показать, что по-прежнему в каждой комнате находится ровно один гость.</p><p>В третьем тестовом случае каждый четвертый гость перемещается в комнату с номером, на $$$1$$$ большим исходного, а остальные гости перемещаются в комнату с номером, на $$$5$$$ большим. Можно показать, что по-прежнему в каждой комнате находится ровно один гость.</p><p>В четвертом тестовом случае гости, исходно находящиеся в комнатах $$$0$$$ и $$$1$$$, перемещаются в комнату с номером $$$3$$$.</p><p>В пятом тестовом случае гости, находящиеся в комнатах $$$1$$$ и $$$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="735cebf38077ebe6feb5766b5cc26b48"/> <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="984a23f77a0946e4a43d943727943ad0eb00b4aa"/> <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='735cebf38077ebe6feb5766b5cc26b48'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1344%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='735cebf38077ebe6feb5766b5cc26b48'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1344">Codeforces Round 639 (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='735cebf38077ebe6feb5766b5cc26b48'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1344/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='735cebf38077ebe6feb5766b5cc26b48'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600701"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='735cebf38077ebe6feb5766b5cc26b48'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600701"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10843" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10856" resourceName="Codeforces Round #639 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/1344">Задачи</a></li> <li><a href="/contest/1344/submit">Отослать</a></li> <li><a href="/contest/1344/my">Мои посылки</a></li> <li><a href="/contest/1344/status">Статус</a></li> <li><a href="/contest/1344/hacks">Взломы</a></li> <li><a href="/contest/1344/room/1">Комната</a></li> <li><a href="/contest/1344/standings">Положение</a></li> <li><a href="/contest/1344/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9f9053c9b53b67feacbc6572072f6f36e7fb7b3a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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-bf">включая ноль и отрицательные числа</span>. Не менее странно то, что сейчас отель полностью заполнен, что означает, что в каждой комнате находится ровно один гость. Менеджер отеля, сам Давид Гильберт, решил переместить гостей, потому что у него есть предположение, что за счет этого образуются свободные места.</p><p>Для любого целого числа $$$k$$$ и положительного целого числа $$$n$$$ обозначим за $$$k\bmod n$$$ остаток при делении числа $$$k$$$ на число $$$n$$$. Более формально, $$$r=k\bmod n$$$ это наименьшее неотрицательное целое число такое, что $$$k-r$$$ делится на $$$n$$$. Всегда выполнено, что $$$0\le k\bmod n\le n-1$$$. Например, $$$100\bmod 12=4$$$ и $$$(-1337)\bmod 3=1$$$.</p><p>Процесс перемещения гостей выглядит следующим образом: есть массив, состоящий из $$$n$$$ целых чисел $$$a_0,a_1,\ldots,a_{n-1}$$$. Тогда для всех целых чисел $$$k$$$ гость из комнаты с номером $$$k$$$ перемещается в комнату с номером $$$k+a_{k\bmod n}$$$.</p><p>Определите, верно ли, что после этого процесса перемещения в каждой комнате по-прежнему находится ровно один гость. Это означает, что нет пустых комнат и комнат, в которых больше одного гостя.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких тестовых случаев. Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество тестовых случаев. Следующие $$$2t$$$ строк содержат описания тестовых случаев.</p><p>В первой строке описания каждого тестового случая находится единственное целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — длина массива.</p><p>Во второй строке описания каждого тестового случая находятся $$$n$$$ целых чисел $$$a_0,a_1,\ldots,a_{n-1}$$$ ($$$-10^9\le a_i\le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите единственную строку, содержащую «<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 1 14 2 1 -1 4 5 5 5 1 3 3 2 1 2 0 1 5 -239 -2 -100 -3 -11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES NO NO YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае номер комнаты каждого гостя увеличился на $$$14$$$, поэтому по-прежнему в каждой комнате находится ровно один гость.</p><p>Во втором тестовом случае гости в комнатах с четными номерами перемещаются в комнату с номером, на $$$1$$$ большим исходного; гости в комнатах с нечетными номерами перемещаются в комнату с номером, на $$$1$$$ меньшим исходного. Можно показать, что по-прежнему в каждой комнате находится ровно один гость.</p><p>В третьем тестовом случае каждый четвертый гость перемещается в комнату с номером, на $$$1$$$ большим исходного, а остальные гости перемещаются в комнату с номером, на $$$5$$$ большим. Можно показать, что по-прежнему в каждой комнате находится ровно один гость.</p><p>В четвертом тестовом случае гости, исходно находящиеся в комнатах $$$0$$$ и $$$1$$$, перемещаются в комнату с номером $$$3$$$.</p><p>В пятом тестовом случае гости, находящиеся в комнатах $$$1$$$ и $$$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 11:02: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:'81249f291cce9d9c',t:'MTY5NjY2NTc0NS4wNDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"]
1344B
1344
B
ru
B. Однополюсные магниты
<div class="problem-statement"><div class="header"><div class="title">B. Однополюсные магниты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Однополюсный магнит — это магнит, у которого ровно один полюс: либо северный, либо южный. Они не существуют в природе, потому что настоящие магниты имеют два полюса, но это задача по программированию, поэтому будем считать, что такие магниты существуют.</p><p>У вас есть таблица размером $$$n\times m$$$. Изначально вы можете поставить несколько магнитов с северным полюсом и несколько магнитов с южным полюсом в некоторые клетки этой таблицы. Вам разрешено расставлять сколько угодно магнитов, в том числе несколько в одну клетку.</p><p>Можно выполнять следующую операцию: выбрать один магнит с северным полюсом и один магнит с южным полюсом для активации. Если они находятся в одной строке или в одном столбце, но занимают разные клетки, то магнит с северным полюсом переместится на одну клетку ближе к магниту с южным полюсом. Иначе, если они занимают одинаковые клетки или не находятся в одной строке или в одном столбце, то ничего не произойдет. Обратите внимание, что магниты с южным полюсом неподвижны.</p><p>Каждая клетка таблицы покрашена в черный или белый цвет. Будем рассматривать расстановки магнитов в таблице, для которых следующие условия будут выполнены.</p><ol> <li> В каждой строке и каждом столбце таблицы находится хотя бы один магнит с южным полюсом. </li><li> Если клетка таблицы черная, тогда можно переместить какой-нибудь магнит с северным полюсом в эту клетку с помощью некоторой последовательности операций <span class="tex-font-style-bf">из начального расположения магнитов</span>. </li><li> Если клетка таблицы белая, тогда никакой магнит с северным полюсом невозможно переместить в эту клетку с помощью некоторой последовательности операций <span class="tex-font-style-bf">из начального расположения магнитов</span>. </li></ol><p>Определите, можно ли расположить магниты в таблице так, что все условия будут выполнены. Если это возможно, найдите минимальное количество магнитов с северным полюсом, которое для этого требуется (минимизировать количество магнитов с южным полюсом не нужно).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$1\le n,m\le 1000$$$)  — количество строк и столбцов в таблице, соответственно.</p><p>Следующие $$$n$$$ строк описывают раскраску таблицы: $$$i$$$-я из этих строк содержит строку длины $$$m$$$, в которой $$$j$$$-й символ обозначает цвет клетки таблицы, находящейся в строке $$$i$$$ и столбце $$$j$$$. Символы «<span class="tex-font-style-tt">#</span>» и «<span class="tex-font-style-tt">.</span>» обозначают черный и белый цвета соответственно. Гарантируется, что строка не содержит других символов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число, которое равно минимальному количеству магнитов с северным полюсом, которое требуется.</p><p>Если не существует способа расставить магниты, который будет удовлетворять всем условиям, выведите единственное целое число $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 .#. ### ##. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 ## .# .# ## </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 ....# ####. .###. .#... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 . # </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 ..... ..... ..... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте возможно расположить магниты следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f89d8c7a378384a96c7e162b53499c211fbb21cd.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором тесте можно показать, что не существует необходимых расположений магнитов. На следующей картинке показаны три примера расположений, которые удовлетворяют не всем условиям. Первый пример нарушает правило $$$3$$$, потому что мы можем переместить магнит с северным полюсом вниз на белую клетку. Второй пример нарушает правило $$$2$$$, потому что мы не можем переместить магнит с северным полюсом в левую нижнюю черную клетку никакой последовательностью операций. Третий пример нарушает правило $$$1$$$, потому что нет ни одного магнита с южным полюсом в первом столбце.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4bf25d94e49a452e00895f940f4e76d26d8cde35.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Следующая картинка показывает пример возможного расположения магнитов в третьем тесте. Можно показать, что не существует необходимых расположений магнитов с меньшим количеством магнитов с северным полюсом.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/730abcba1dab5abea574d5f479fe54cdf3f528ae.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во четвертом тесте можно показать, что не существует необходимых расположений магнитов. На следующей картинке два примера расположений, которые удовлетворяют не всем условиям. Первый пример нарушает правило $$$1$$$, потому что нет ни одного магнита с южным полюсом в первой строке. Второй пример нарушает правила $$$1$$$ и $$$3$$$, потому что нет ни одного магнита с южным полюсом во второй строке, а кроме того, мы можем переместить магнит с северным полюсом на одну клетку вверх, и он попадет на белую клетку.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c719c90077972d8befc8234a02d55b35d7736299.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В пятом тесте мы можем поставить магниты с южным полюсом во все клетки и не использовать ни одного магнита с северным полюсом. Поскольку нет ни одной черной клетки, это будет корректной расстановкой магнитов.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="224c0e9d812b15ac6af7a7828f973051"/> <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="984a23f77a0946e4a43d943727943ad0eb00b4aa"/> <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='224c0e9d812b15ac6af7a7828f973051'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1344%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='224c0e9d812b15ac6af7a7828f973051'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1344">Codeforces Round 639 (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='224c0e9d812b15ac6af7a7828f973051'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1344/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound 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='224c0e9d812b15ac6af7a7828f973051'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600702"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='224c0e9d812b15ac6af7a7828f973051'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600702"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10843" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10856" resourceName="Codeforces Round #639 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/1344">Задачи</a></li> <li><a href="/contest/1344/submit">Отослать</a></li> <li><a href="/contest/1344/my">Мои посылки</a></li> <li><a href="/contest/1344/status">Статус</a></li> <li><a href="/contest/1344/hacks">Взломы</a></li> <li><a href="/contest/1344/room/1">Комната</a></li> <li><a href="/contest/1344/standings">Положение</a></li> <li><a href="/contest/1344/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1b01feea610db21f8c9c7d886c8be828ba3efa79"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Однополюсные магниты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Однополюсный магнит — это магнит, у которого ровно один полюс: либо северный, либо южный. Они не существуют в природе, потому что настоящие магниты имеют два полюса, но это задача по программированию, поэтому будем считать, что такие магниты существуют.</p><p>У вас есть таблица размером $$$n\times m$$$. Изначально вы можете поставить несколько магнитов с северным полюсом и несколько магнитов с южным полюсом в некоторые клетки этой таблицы. Вам разрешено расставлять сколько угодно магнитов, в том числе несколько в одну клетку.</p><p>Можно выполнять следующую операцию: выбрать один магнит с северным полюсом и один магнит с южным полюсом для активации. Если они находятся в одной строке или в одном столбце, но занимают разные клетки, то магнит с северным полюсом переместится на одну клетку ближе к магниту с южным полюсом. Иначе, если они занимают одинаковые клетки или не находятся в одной строке или в одном столбце, то ничего не произойдет. Обратите внимание, что магниты с южным полюсом неподвижны.</p><p>Каждая клетка таблицы покрашена в черный или белый цвет. Будем рассматривать расстановки магнитов в таблице, для которых следующие условия будут выполнены.</p><ol> <li> В каждой строке и каждом столбце таблицы находится хотя бы один магнит с южным полюсом. </li><li> Если клетка таблицы черная, тогда можно переместить какой-нибудь магнит с северным полюсом в эту клетку с помощью некоторой последовательности операций <span class="tex-font-style-bf">из начального расположения магнитов</span>. </li><li> Если клетка таблицы белая, тогда никакой магнит с северным полюсом невозможно переместить в эту клетку с помощью некоторой последовательности операций <span class="tex-font-style-bf">из начального расположения магнитов</span>. </li></ol><p>Определите, можно ли расположить магниты в таблице так, что все условия будут выполнены. Если это возможно, найдите минимальное количество магнитов с северным полюсом, которое для этого требуется (минимизировать количество магнитов с южным полюсом не нужно).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$1\le n,m\le 1000$$$)  — количество строк и столбцов в таблице, соответственно.</p><p>Следующие $$$n$$$ строк описывают раскраску таблицы: $$$i$$$-я из этих строк содержит строку длины $$$m$$$, в которой $$$j$$$-й символ обозначает цвет клетки таблицы, находящейся в строке $$$i$$$ и столбце $$$j$$$. Символы «<span class="tex-font-style-tt">#</span>» и «<span class="tex-font-style-tt">.</span>» обозначают черный и белый цвета соответственно. Гарантируется, что строка не содержит других символов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число, которое равно минимальному количеству магнитов с северным полюсом, которое требуется.</p><p>Если не существует способа расставить магниты, который будет удовлетворять всем условиям, выведите единственное целое число $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 .#. ### ##. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 ## .# .# ## </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 ....# ####. .###. .#... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 . # </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 ..... ..... ..... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте возможно расположить магниты следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f89d8c7a378384a96c7e162b53499c211fbb21cd.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором тесте можно показать, что не существует необходимых расположений магнитов. На следующей картинке показаны три примера расположений, которые удовлетворяют не всем условиям. Первый пример нарушает правило $$$3$$$, потому что мы можем переместить магнит с северным полюсом вниз на белую клетку. Второй пример нарушает правило $$$2$$$, потому что мы не можем переместить магнит с северным полюсом в левую нижнюю черную клетку никакой последовательностью операций. Третий пример нарушает правило $$$1$$$, потому что нет ни одного магнита с южным полюсом в первом столбце.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4bf25d94e49a452e00895f940f4e76d26d8cde35.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Следующая картинка показывает пример возможного расположения магнитов в третьем тесте. Можно показать, что не существует необходимых расположений магнитов с меньшим количеством магнитов с северным полюсом.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/730abcba1dab5abea574d5f479fe54cdf3f528ae.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во четвертом тесте можно показать, что не существует необходимых расположений магнитов. На следующей картинке два примера расположений, которые удовлетворяют не всем условиям. Первый пример нарушает правило $$$1$$$, потому что нет ни одного магнита с южным полюсом в первой строке. Второй пример нарушает правила $$$1$$$ и $$$3$$$, потому что нет ни одного магнита с южным полюсом во второй строке, а кроме того, мы можем переместить магнит с северным полюсом на одну клетку вверх, и он попадет на белую клетку.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c719c90077972d8befc8234a02d55b35d7736299.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В пятом тесте мы можем поставить магниты с южным полюсом во все клетки и не использовать ни одного магнита с северным полюсом. Поскольку нет ни одной черной клетки, это будет корректной расстановкой магнитов.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=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 11:02: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:'81249f3258471693',t:'MTY5NjY2NTc0Ni41NTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\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", "\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\u043d\u043c", "*2000"]
1344C
1344
C
ru
C. Задача про кванторы
<div class="problem-statement"><div class="header"><div class="title">C. Задача про кванторы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Логические кванторы — это очень хороший инструмент для создания некоторых утверждений о множестве. В этой задаче мы будем рассматривать множество вещественных чисел. <span class="tex-font-style-bf">Множество вещественных чисел содержит ноль и отрицательные числа.</span> Есть два вида кванторов: всеобщности ($$$\forall$$$) и существования ($$$\exists$$$). Вы можете прочитать больше про них <a href="https://ru.wikipedia.org/wiki/Квантор">здесь</a>.</p><p>Квантор всеобщности используется, чтобы сказать, что утверждение выполнено <span class="tex-font-style-it">для всех вещественных чисел</span>. Например:</p><ul> <li> $$$\forall x,x&lt;100$$$ читается как: для всех вещественных чисел $$$x$$$ число $$$x$$$ меньше, чем $$$100$$$. Это утверждение ложно. </li><li> $$$\forall x,x&gt;x-1$$$ читается как: для всех вещественных чисел $$$x$$$ число $$$x$$$ больше, чем $$$x-1$$$. Это утверждение верно. </li></ul><p>Квантор существования используется, чтобы сказать, что <span class="tex-font-style-it">существует некоторое вещественное число</span>, для которого утверждение выполнено. Например:</p><ul> <li> $$$\exists x,x&lt;100$$$ читается как: существует вещественное число $$$x$$$ такое, что $$$x$$$ меньше, чем $$$100$$$. Это утверждение верно. </li><li> $$$\exists x,x&gt;x-1$$$ читается как: существует вещественное число $$$x$$$ такое, что $$$x$$$ больше, чем $$$x-1$$$. Это утверждение верно. </li></ul><p>Кроме того, эти кванторы могут быть вложенными. Например:</p><ul> <li> $$$\forall x,\exists y,x&lt;y$$$ читается так: для всех вещественных чисел $$$x$$$ существует вещественное число $$$y$$$ такое, что $$$x$$$ меньше, чем $$$y$$$. Это утверждение верно для всех $$$x$$$, потому что существует $$$y=x+1$$$. </li><li> $$$\exists y,\forall x,x&lt;y$$$ читается так: существует вещественное число $$$y$$$ такое, что для всех вещественных чисел $$$x$$$ число $$$x$$$ меньше, чем $$$y$$$. Это утверждение ложно, потому что оно утверждает, что существует максимальное вещественное число: число $$$y$$$ больше, чем любое $$$x$$$. </li></ul><p><span class="tex-font-style-bf">Обратите внимание, что порядок переменных и кванторов важен для значения и верности утверждения.</span></p><p>Всего есть $$$n$$$ переменных $$$x_1,x_2,\ldots,x_n$$$, и вам дана формула вида $$$$$$ f(x_1,\dots,x_n):=(x_{j_1}&lt;x_{k_1})\land (x_{j_2}&lt;x_{k_2})\land \cdots\land (x_{j_m}&lt;x_{k_m}), $$$$$$</p><p>где $$$\land$$$ обозначает логическое И. Это означает, что $$$f(x_1,\ldots, x_n)$$$ истинно, если каждое неравенство $$$x_{j_i}&lt;x_{k_i}$$$ выполнено. Иначе, если хотя бы одно неравенство не выполнено, то $$$f(x_1,\ldots,x_n)$$$ ложно.</p><p>Ваша задача — выбрать значения каждого из кванторов $$$Q_1,\ldots,Q_n$$$ либо квантором всеобщности ($$$\forall$$$), либо квантором существования ($$$\exists$$$) так, что утверждение $$$$$$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$$$$$</p><p>будет верно и <span class="tex-font-style-bf">количество кванторов всеобщности максимально возможное</span>, или определить, что утверждение ложно для всех возможных выборов кванторов.</p><p><span class="tex-font-style-bf">Обратите внимание, что порядок переменных, в котором они идут в утверждении фиксирован.</span> Например, если $$$f(x_1,x_2):=(x_1&lt;x_2)$$$, то вам не разрешено сделать переменную $$$x_2$$$ идущей первой, и получить утверждение $$$\forall x_2,\exists x_1, x_1&lt;x_2$$$. Если вы выберете $$$Q_1=\exists$$$ и $$$Q_2=\forall$$$ получившееся утверждение будет <span class="tex-font-style-bf">однозначно</span> равно $$$\exists x_1,\forall x_2,x_1&lt;x_2$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$; $$$1\le m\le 2\cdot 10^5$$$) — количество переменных и неравенств в формуле, соответственно.</p><p>Следующие $$$m$$$ строк описывают формулу. $$$i$$$-я из этих строк содержит два целых числа $$$j_i$$$, $$$k_i$$$ ($$$1\le j_i,k_i\le n$$$, $$$j_i\ne k_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если ни одной расстановки кванторов такой, что утверждение будет верно, не существует, выведите единственное целое число $$$-1$$$.</p><p>Иначе на первой строке выведите максимальное возможное количество кванторов всеобщности.</p><p>На следующей строке выведите строку длины $$$n$$$, в которой $$$i$$$-й символ это «<span class="tex-font-style-tt">A</span>», если $$$Q_i$$$ должен быть квантором всеобщности ($$$\forall$$$), или «<span class="tex-font-style-tt">E</span>», если $$$Q_i$$$ должен быть квантором существования ($$$\exists$$$). Все символы должны быть в верхнем регистре. Если существует несколько возможных решений, в которых количество кванторов всеобщности максимально возможное, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 AE </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 2 3 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 1 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 AAE </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте утверждение $$$\forall x_1, \exists x_2, x_1&lt;x_2$$$ верно. Ответы «<span class="tex-font-style-tt">EA</span>» и «<span class="tex-font-style-tt">AA</span>» дают ложные утверждения. Ответ «<span class="tex-font-style-tt">EE</span>» дает верное утверждение, но количество кванторов всеобщности будет меньше, чем в нашем ответе.</p><p>Для второго теста можно показать, что ни одной расстановки кванторов такой, что утверждение будет верно, не существует.</p><p>В третьем тесте утверждение $$$\forall x_1, \forall x_2, \exists x_3, (x_1&lt;x_3)\land (x_2&lt;x_3)$$$ верно: мы можем выбрать $$$x_3=\max\{x_1,x_2\}+1$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e0936ac63cc3b5b787a1af8af1394543"/> <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="984a23f77a0946e4a43d943727943ad0eb00b4aa"/> <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='e0936ac63cc3b5b787a1af8af1394543'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1344%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='e0936ac63cc3b5b787a1af8af1394543'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1344">Codeforces Round 639 (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='e0936ac63cc3b5b787a1af8af1394543'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1344/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='e0936ac63cc3b5b787a1af8af1394543'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600703"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e0936ac63cc3b5b787a1af8af1394543'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600703"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10843" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10856" resourceName="Codeforces Round #639 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/1344">Задачи</a></li> <li><a href="/contest/1344/submit">Отослать</a></li> <li><a href="/contest/1344/my">Мои посылки</a></li> <li><a href="/contest/1344/status">Статус</a></li> <li><a href="/contest/1344/hacks">Взломы</a></li> <li><a href="/contest/1344/room/1">Комната</a></li> <li><a href="/contest/1344/standings">Положение</a></li> <li><a href="/contest/1344/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9ce5632addfccd1c147b8e4a78c355a0f227d489"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Задача про кванторы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Логические кванторы — это очень хороший инструмент для создания некоторых утверждений о множестве. В этой задаче мы будем рассматривать множество вещественных чисел. <span class="tex-font-style-bf">Множество вещественных чисел содержит ноль и отрицательные числа.</span> Есть два вида кванторов: всеобщности ($$$\forall$$$) и существования ($$$\exists$$$). Вы можете прочитать больше про них <a href="https://ru.wikipedia.org/wiki/Квантор">здесь</a>.</p><p>Квантор всеобщности используется, чтобы сказать, что утверждение выполнено <span class="tex-font-style-it">для всех вещественных чисел</span>. Например:</p><ul> <li> $$$\forall x,x&lt;100$$$ читается как: для всех вещественных чисел $$$x$$$ число $$$x$$$ меньше, чем $$$100$$$. Это утверждение ложно. </li><li> $$$\forall x,x&gt;x-1$$$ читается как: для всех вещественных чисел $$$x$$$ число $$$x$$$ больше, чем $$$x-1$$$. Это утверждение верно. </li></ul><p>Квантор существования используется, чтобы сказать, что <span class="tex-font-style-it">существует некоторое вещественное число</span>, для которого утверждение выполнено. Например:</p><ul> <li> $$$\exists x,x&lt;100$$$ читается как: существует вещественное число $$$x$$$ такое, что $$$x$$$ меньше, чем $$$100$$$. Это утверждение верно. </li><li> $$$\exists x,x&gt;x-1$$$ читается как: существует вещественное число $$$x$$$ такое, что $$$x$$$ больше, чем $$$x-1$$$. Это утверждение верно. </li></ul><p>Кроме того, эти кванторы могут быть вложенными. Например:</p><ul> <li> $$$\forall x,\exists y,x&lt;y$$$ читается так: для всех вещественных чисел $$$x$$$ существует вещественное число $$$y$$$ такое, что $$$x$$$ меньше, чем $$$y$$$. Это утверждение верно для всех $$$x$$$, потому что существует $$$y=x+1$$$. </li><li> $$$\exists y,\forall x,x&lt;y$$$ читается так: существует вещественное число $$$y$$$ такое, что для всех вещественных чисел $$$x$$$ число $$$x$$$ меньше, чем $$$y$$$. Это утверждение ложно, потому что оно утверждает, что существует максимальное вещественное число: число $$$y$$$ больше, чем любое $$$x$$$. </li></ul><p><span class="tex-font-style-bf">Обратите внимание, что порядок переменных и кванторов важен для значения и верности утверждения.</span></p><p>Всего есть $$$n$$$ переменных $$$x_1,x_2,\ldots,x_n$$$, и вам дана формула вида $$$$$$ f(x_1,\dots,x_n):=(x_{j_1}&lt;x_{k_1})\land (x_{j_2}&lt;x_{k_2})\land \cdots\land (x_{j_m}&lt;x_{k_m}), $$$$$$</p><p>где $$$\land$$$ обозначает логическое И. Это означает, что $$$f(x_1,\ldots, x_n)$$$ истинно, если каждое неравенство $$$x_{j_i}&lt;x_{k_i}$$$ выполнено. Иначе, если хотя бы одно неравенство не выполнено, то $$$f(x_1,\ldots,x_n)$$$ ложно.</p><p>Ваша задача — выбрать значения каждого из кванторов $$$Q_1,\ldots,Q_n$$$ либо квантором всеобщности ($$$\forall$$$), либо квантором существования ($$$\exists$$$) так, что утверждение $$$$$$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$$$$$</p><p>будет верно и <span class="tex-font-style-bf">количество кванторов всеобщности максимально возможное</span>, или определить, что утверждение ложно для всех возможных выборов кванторов.</p><p><span class="tex-font-style-bf">Обратите внимание, что порядок переменных, в котором они идут в утверждении фиксирован.</span> Например, если $$$f(x_1,x_2):=(x_1&lt;x_2)$$$, то вам не разрешено сделать переменную $$$x_2$$$ идущей первой, и получить утверждение $$$\forall x_2,\exists x_1, x_1&lt;x_2$$$. Если вы выберете $$$Q_1=\exists$$$ и $$$Q_2=\forall$$$ получившееся утверждение будет <span class="tex-font-style-bf">однозначно</span> равно $$$\exists x_1,\forall x_2,x_1&lt;x_2$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$; $$$1\le m\le 2\cdot 10^5$$$) — количество переменных и неравенств в формуле, соответственно.</p><p>Следующие $$$m$$$ строк описывают формулу. $$$i$$$-я из этих строк содержит два целых числа $$$j_i$$$, $$$k_i$$$ ($$$1\le j_i,k_i\le n$$$, $$$j_i\ne k_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если ни одной расстановки кванторов такой, что утверждение будет верно, не существует, выведите единственное целое число $$$-1$$$.</p><p>Иначе на первой строке выведите максимальное возможное количество кванторов всеобщности.</p><p>На следующей строке выведите строку длины $$$n$$$, в которой $$$i$$$-й символ это «<span class="tex-font-style-tt">A</span>», если $$$Q_i$$$ должен быть квантором всеобщности ($$$\forall$$$), или «<span class="tex-font-style-tt">E</span>», если $$$Q_i$$$ должен быть квантором существования ($$$\exists$$$). Все символы должны быть в верхнем регистре. Если существует несколько возможных решений, в которых количество кванторов всеобщности максимально возможное, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 AE </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 2 3 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 1 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 AAE </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте утверждение $$$\forall x_1, \exists x_2, x_1&lt;x_2$$$ верно. Ответы «<span class="tex-font-style-tt">EA</span>» и «<span class="tex-font-style-tt">AA</span>» дают ложные утверждения. Ответ «<span class="tex-font-style-tt">EE</span>» дает верное утверждение, но количество кванторов всеобщности будет меньше, чем в нашем ответе.</p><p>Для второго теста можно показать, что ни одной расстановки кванторов такой, что утверждение будет верно, не существует.</p><p>В третьем тесте утверждение $$$\forall x_1, \forall x_2, \exists x_3, (x_1&lt;x_3)\land (x_2&lt;x_3)$$$ верно: мы можем выбрать $$$x_3=\max\{x_1,x_2\}+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 11:02: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:'81249f3bca384995',t:'MTY5NjY2NTc0Ny45ODYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2600"]
1344D
1344
D
ru
D. Составление резюме
<div class="problem-statement"><div class="header"><div class="title">D. Составление резюме</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">О нет! Скоро закончится время, когда еще можно подать заявку на стажировку в IT компанию, а вы медлили, участвуя в контестах вместо этого! (Давайте пока притворимся, что в наше неопределенное время можно будет найти работу.)</span></p><p>Вы сделали много проектов по программированию. Существует ровно $$$n$$$ типов проектов и вы сделали $$$a_i$$$ проектов типа $$$i$$$. Ваше резюме имеет ограниченный размер, но вы хотите аккуратно выбрать проекты, чтобы максимизировать шанс того, что вас возьмут на работу.</p><p>Вы хотите включить несколько проектов одного типа, чтобы подчеркнуть вашу компетентность, но вы также не хотите включать их так много, что среди них начнут появляться некачественные проекты. Поэтому, вы придумали следующую формулу, которая является хорошим индикатором того, что вас возьмут на работу:</p><p>$$$$$$ f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). $$$$$$</p><p>Здесь $$$b_i$$$ обозначает количество проектов типа $$$i$$$, которое вы включите в ваше резюме. Конечно, вы не можете включить в резюме больше проектов, чем вы сделали, поэтому для всех $$$i$$$ должно быть выполнено $$$0\le b_i \le a_i$$$.</p><p>В вашем резюме хватает места для $$$k$$$ проектов, и вы абсолютно точно не будете приняты на работу, если в вашем резюме будет пустая строчка. Поэтому вы хотите, чтобы было выполнено $$$\sum\limits_{i=1}^n b_i=k$$$.</p><p>Найдите значения $$$b_1,\ldots, b_n$$$, которые максимизируют значение $$$f(b_1,\ldots,b_n)$$$ при том, что все описанные условия выполнены.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$k$$$ ($$$1\le n\le 10^5$$$, $$$1\le k\le \sum\limits_{i=1}^n a_i$$$) — количество типов проектов и размер резюме, соответственно.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$), $$$a_i$$$ равно количеству сделанных проектов типа $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$n$$$ целых чисел $$$b_1,\ldots, b_n$$$, для которых достигается максимальное значение $$$f(b_1,\ldots,b_n)$$$ в условиях ограничений $$$0\le b_i\le a_i$$$ и $$$\sum\limits_{i=1}^n b_i=k$$$. Если существует несколько возможных решений, выведите любое.</p><p><span class="tex-font-style-bf">Обратите внимание, что вы не должны выводить само значение $$$f(b_1,\ldots,b_n)$$$.</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 32 1 2 3 4 5 5 5 5 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 3 4 4 4 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 8 4 4 8 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 2 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте оптимальный ответ это $$$f=-269$$$. Обратите внимание, что большее значение $$$f$$$ возможно, только если мы уберем ограничение $$$\sum\limits_{i=1}^n b_i=k$$$.</p><p>Во втором тесте оптимальный ответ $$$f=9$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="bc1aa6a4cd79e40ecb6978428fc03f4f"/> <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="984a23f77a0946e4a43d943727943ad0eb00b4aa"/> <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='bc1aa6a4cd79e40ecb6978428fc03f4f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1344%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='bc1aa6a4cd79e40ecb6978428fc03f4f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1344">Codeforces Round 639 (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='bc1aa6a4cd79e40ecb6978428fc03f4f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1344/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='bc1aa6a4cd79e40ecb6978428fc03f4f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600704"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bc1aa6a4cd79e40ecb6978428fc03f4f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600704"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10843" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10856" resourceName="Codeforces Round #639 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/1344">Задачи</a></li> <li><a href="/contest/1344/submit">Отослать</a></li> <li><a href="/contest/1344/my">Мои посылки</a></li> <li><a href="/contest/1344/status">Статус</a></li> <li><a href="/contest/1344/hacks">Взломы</a></li> <li><a href="/contest/1344/room/1">Комната</a></li> <li><a href="/contest/1344/standings">Положение</a></li> <li><a href="/contest/1344/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_926f45e990b72906ec2ed85ce747784f1ae33119"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Составление резюме</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">О нет! Скоро закончится время, когда еще можно подать заявку на стажировку в IT компанию, а вы медлили, участвуя в контестах вместо этого! (Давайте пока притворимся, что в наше неопределенное время можно будет найти работу.)</span></p><p>Вы сделали много проектов по программированию. Существует ровно $$$n$$$ типов проектов и вы сделали $$$a_i$$$ проектов типа $$$i$$$. Ваше резюме имеет ограниченный размер, но вы хотите аккуратно выбрать проекты, чтобы максимизировать шанс того, что вас возьмут на работу.</p><p>Вы хотите включить несколько проектов одного типа, чтобы подчеркнуть вашу компетентность, но вы также не хотите включать их так много, что среди них начнут появляться некачественные проекты. Поэтому, вы придумали следующую формулу, которая является хорошим индикатором того, что вас возьмут на работу:</p><p>$$$$$$ f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). $$$$$$</p><p>Здесь $$$b_i$$$ обозначает количество проектов типа $$$i$$$, которое вы включите в ваше резюме. Конечно, вы не можете включить в резюме больше проектов, чем вы сделали, поэтому для всех $$$i$$$ должно быть выполнено $$$0\le b_i \le a_i$$$.</p><p>В вашем резюме хватает места для $$$k$$$ проектов, и вы абсолютно точно не будете приняты на работу, если в вашем резюме будет пустая строчка. Поэтому вы хотите, чтобы было выполнено $$$\sum\limits_{i=1}^n b_i=k$$$.</p><p>Найдите значения $$$b_1,\ldots, b_n$$$, которые максимизируют значение $$$f(b_1,\ldots,b_n)$$$ при том, что все описанные условия выполнены.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$k$$$ ($$$1\le n\le 10^5$$$, $$$1\le k\le \sum\limits_{i=1}^n a_i$$$) — количество типов проектов и размер резюме, соответственно.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$), $$$a_i$$$ равно количеству сделанных проектов типа $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$n$$$ целых чисел $$$b_1,\ldots, b_n$$$, для которых достигается максимальное значение $$$f(b_1,\ldots,b_n)$$$ в условиях ограничений $$$0\le b_i\le a_i$$$ и $$$\sum\limits_{i=1}^n b_i=k$$$. Если существует несколько возможных решений, выведите любое.</p><p><span class="tex-font-style-bf">Обратите внимание, что вы не должны выводить само значение $$$f(b_1,\ldots,b_n)$$$.</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 32 1 2 3 4 5 5 5 5 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 3 4 4 4 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 8 4 4 8 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 2 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте оптимальный ответ это $$$f=-269$$$. Обратите внимание, что большее значение $$$f$$$ возможно, только если мы уберем ограничение $$$\sum\limits_{i=1}^n b_i=k$$$.</p><p>Во втором тесте оптимальный ответ $$$f=9$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'81249f44acca0056',t:'MTY5NjY2NTc0OS40ODcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2700"]
1344E
1344
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><span class="tex-font-style-it">Все верно. Я студент университета Пердью и безо всякого стыда придумал задачу про поезда.</span></p><p>Есть $$$n$$$ станций и $$$m$$$ поездов. Станции соединяются $$$n-1$$$ однонаправленной железной дорогой так, что они образуют корневое дерево с корнем в станции $$$1$$$. Все железные дороги имеют направлены вдоль путей от корневой станции $$$1$$$ к листьям. Каждая железная дорога ведет от станции $$$u$$$ к станции $$$v$$$ и имеет расстояние $$$d$$$, обозначающее, что требуется $$$d$$$ единиц времени, чтобы доехать от станции $$$u$$$ к станции $$$v$$$. Каждая станция, из которой выходит хотя бы одна железная дорога, имеет переключатель, который определяет станцию, в которую затем поедет любой поезд, приехавший на эту станцию. Например, это может выглядеть следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a8bd088972a0dd07d182e1561fc0906f02f5b734.png" style="max-width: 100.0%;max-height: 100.0%;"/> Здесь станции $$$1$$$ и $$$3$$$ имеют переключатели, направляющие к станциям $$$2$$$ и $$$4$$$, соответственно. </center><p>Изначально ни на одной станции нет поезда. Поезд $$$i$$$ появится на станции $$$1$$$ в момент времени $$$t_i$$$. В каждый момент времени, начиная с $$$1$$$, будут происходить следующие два шага:</p><ol> <li> Вы можете переключить переключатель не более одной станции на другую дорогу, выходящую из этой станции. Переключение происходит до шага $$$2$$$. </li><li> Любой поезд, который находится на станции $$$u$$$, направляется к станции $$$v$$$, в которую указывает переключатель станции $$$u$$$. Если железная дорога от станции $$$u$$$ к станции $$$v$$$ имела расстояние $$$d$$$, поезд прибудет на станцию $$$v$$$ через $$$d$$$ единиц времени от настоящего момента. </li></ol><p>У каждого поезда есть станция прибытия $$$s_i$$$. Когда он прибывает на станцию $$$s_i$$$, он останавливается там навсегда. Если в какой-то момент времени поезд поедет в неверном направлении, то есть он никогда уже не сможет достичь станции $$$s_i$$$ независимо от состояния переключателей, он тут же взорвется.</p><p>Найдите <span class="tex-font-style-bf">наибольшее возможное время первого взрыва</span>, если вы будете переключать переключатели оптимально или определите, что вы можете направить каждый поезд к своей станции прибытия так, что ни одного взрыва не произойдет. Также найдите <span class="tex-font-style-bf">минимальное количество переключений</span>, которое требуется, чтобы достичь этого.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$1\le n,m\le 10^5$$$) — количество станций и поездов, соответственно.</p><p>Следующие $$$n-1$$$ строк описывают железные дороги. $$$i$$$-я из этих строк содержит три целых числа $$$u,v,d$$$ ($$$1\le u,v\le n$$$, $$$1\le d\le 10^9$$$), обозначающие железную дорогу от станции $$$u$$$ к станции $$$v$$$, имеющую расстояние $$$d$$$. Гарантируется, что железные дороги формируют корневое дерево с корнем в станции $$$1$$$. <span class="tex-font-style-bf">Переключатель в станции $$$u$$$ изначально направлен вдоль последней в данном порядке железной дороги, выходящей из станции $$$u$$$.</span></p><p>Следующие $$$m$$$ строк описывают поезда. $$$i$$$-я из этих строк содержит два целых числа $$$s_i,t_i$$$ ($$$1\le s_i\le n$$$, $$$1\le t_1&lt;t_2&lt;\cdots&lt;t_m\le 10^9$$$) — станция назначения и время, в которое $$$i$$$-й поезд прибудет на станцию $$$1$$$, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа: наибольшее возможное время первого взрыва (или $$$-1$$$, если можно предотвратить взрывы) и минимальное количество переключений, необходимое, чтобы достичь этого.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 1 2 1 1 3 2 3 4 1 3 5 3 2 1 4 2 2 6 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 1 2 1 1 3 2 3 4 1 3 5 3 5 1 4 2 4 3 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 11 6 1 2 1 1 3 2 3 4 1 3 5 2 5 6 1 5 7 2 7 8 1 7 9 2 9 10 1 9 11 1 2 1 8 3 6 5 10 7 4 9 2 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте один из возможных примеров того, как все будет происходить, описан ниже. </p><ul> <li> В момент времени $$$1$$$ поезд $$$1$$$ прибывает на станцию $$$1$$$. Переключатель станции $$$1$$$ направлен к станции $$$2$$$. Поезд $$$1$$$ отправляется к станции $$$2$$$. </li><li> В момент времени $$$2$$$ поезд $$$2$$$ прибывает на станцию $$$1$$$ и поезд $$$1$$$ прибывает на станцию $$$2$$$, где останавливается навсегда. Мы переключаем переключатель в станции $$$1$$$ к станции $$$3$$$. Поезд $$$2$$$ направляется к станции $$$3$$$. </li><li> В момент времени $$$4$$$ поезд $$$2$$$ прибывает на станцию $$$3$$$. Мы переключаем переключатель в станции $$$3$$$ к станции $$$4$$$. Поезд $$$2$$$ направляется к станции $$$4$$$. </li><li> В момент времени $$$5$$$ поезд $$$2$$$ прибывает на станцию $$$4$$$, где останавливается навсегда. </li><li> В момент времени $$$6$$$ поезд $$$3$$$ прибывает на станцию $$$1$$$. Мы переключаем переключатель станции $$$1$$$ к станции $$$2$$$. Поезд $$$3$$$ направляется к станции $$$2$$$. </li><li> В момент времени $$$7$$$ поезд $$$3$$$ прибывает на станцию $$$2$$$, где останавливается навсегда. Мы переключаем переключатель станции $$$3$$$ к станции $$$5$$$. </li><li> В момент времени $$$10$$$ поезд $$$4$$$ прибывает на станцию $$$1$$$. Мы переключаем переключатель станции $$$1$$$ к станции $$$3$$$. Поезд $$$4$$$ направляется к станции $$$3$$$. </li><li> В момент времени $$$12$$$ поезд $$$4$$$ прибывает на станцию $$$3$$$. Поезд $$$4$$$ направляется к станции $$$5$$$. </li><li> В момент времени $$$15$$$ поезд $$$4$$$ прибывает на станцию $$$5$$$, где останавливается навсегда. </li></ul><p>Во втором тесте мы не переключаем ничего. В момент времени $$$4$$$ поезд $$$2$$$ направляется к станции $$$5$$$, и поезд $$$4$$$ направляется к станции $$$3$$$. Они оба взрываются. Невозможно предотвратить взрывы поездов к моменту времени $$$4$$$.</p><p>В третьем тесте давайте будем обозначать переключение переключателя как $$$(u\to v,t)$$$, если мы переключаем переключатель станции $$$u$$$ к станции $$$v$$$ в момент времени $$$t$$$. Одним из решений является сделать следующие $$$4$$$ переключения: $$$(1\to 2,1)$$$, $$$(1\to 3,2)$$$, $$$(7\to 8,5)$$$, $$$(5\to 6,8)$$$. В момент времени $$$11$$$ поезда $$$4$$$, $$$5$$$ и $$$6$$$ взорвутся. Невозможно предотвратить взрывы поездов к моменту времени $$$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="3db7e41e7c861dc9369e31d9f3225f0e"/> <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="984a23f77a0946e4a43d943727943ad0eb00b4aa"/> <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='3db7e41e7c861dc9369e31d9f3225f0e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1344%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='3db7e41e7c861dc9369e31d9f3225f0e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1344">Codeforces Round 639 (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='3db7e41e7c861dc9369e31d9f3225f0e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1344/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='3db7e41e7c861dc9369e31d9f3225f0e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600706"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3db7e41e7c861dc9369e31d9f3225f0e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600706"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10843" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10856" resourceName="Codeforces Round #639 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/1344">Задачи</a></li> <li><a href="/contest/1344/submit">Отослать</a></li> <li><a href="/contest/1344/my">Мои посылки</a></li> <li><a href="/contest/1344/status">Статус</a></li> <li><a href="/contest/1344/hacks">Взломы</a></li> <li><a href="/contest/1344/room/1">Комната</a></li> <li><a href="/contest/1344/standings">Положение</a></li> <li><a href="/contest/1344/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7437dcf6ef3226ae4615ab523328dec4631b5e87"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><span class="tex-font-style-it">Все верно. Я студент университета Пердью и безо всякого стыда придумал задачу про поезда.</span></p><p>Есть $$$n$$$ станций и $$$m$$$ поездов. Станции соединяются $$$n-1$$$ однонаправленной железной дорогой так, что они образуют корневое дерево с корнем в станции $$$1$$$. Все железные дороги имеют направлены вдоль путей от корневой станции $$$1$$$ к листьям. Каждая железная дорога ведет от станции $$$u$$$ к станции $$$v$$$ и имеет расстояние $$$d$$$, обозначающее, что требуется $$$d$$$ единиц времени, чтобы доехать от станции $$$u$$$ к станции $$$v$$$. Каждая станция, из которой выходит хотя бы одна железная дорога, имеет переключатель, который определяет станцию, в которую затем поедет любой поезд, приехавший на эту станцию. Например, это может выглядеть следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a8bd088972a0dd07d182e1561fc0906f02f5b734.png" style="max-width: 100.0%;max-height: 100.0%;" /> Здесь станции $$$1$$$ и $$$3$$$ имеют переключатели, направляющие к станциям $$$2$$$ и $$$4$$$, соответственно. </center><p>Изначально ни на одной станции нет поезда. Поезд $$$i$$$ появится на станции $$$1$$$ в момент времени $$$t_i$$$. В каждый момент времени, начиная с $$$1$$$, будут происходить следующие два шага:</p><ol> <li> Вы можете переключить переключатель не более одной станции на другую дорогу, выходящую из этой станции. Переключение происходит до шага $$$2$$$. </li><li> Любой поезд, который находится на станции $$$u$$$, направляется к станции $$$v$$$, в которую указывает переключатель станции $$$u$$$. Если железная дорога от станции $$$u$$$ к станции $$$v$$$ имела расстояние $$$d$$$, поезд прибудет на станцию $$$v$$$ через $$$d$$$ единиц времени от настоящего момента. </li></ol><p>У каждого поезда есть станция прибытия $$$s_i$$$. Когда он прибывает на станцию $$$s_i$$$, он останавливается там навсегда. Если в какой-то момент времени поезд поедет в неверном направлении, то есть он никогда уже не сможет достичь станции $$$s_i$$$ независимо от состояния переключателей, он тут же взорвется.</p><p>Найдите <span class="tex-font-style-bf">наибольшее возможное время первого взрыва</span>, если вы будете переключать переключатели оптимально или определите, что вы можете направить каждый поезд к своей станции прибытия так, что ни одного взрыва не произойдет. Также найдите <span class="tex-font-style-bf">минимальное количество переключений</span>, которое требуется, чтобы достичь этого.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$1\le n,m\le 10^5$$$) — количество станций и поездов, соответственно.</p><p>Следующие $$$n-1$$$ строк описывают железные дороги. $$$i$$$-я из этих строк содержит три целых числа $$$u,v,d$$$ ($$$1\le u,v\le n$$$, $$$1\le d\le 10^9$$$), обозначающие железную дорогу от станции $$$u$$$ к станции $$$v$$$, имеющую расстояние $$$d$$$. Гарантируется, что железные дороги формируют корневое дерево с корнем в станции $$$1$$$. <span class="tex-font-style-bf">Переключатель в станции $$$u$$$ изначально направлен вдоль последней в данном порядке железной дороги, выходящей из станции $$$u$$$.</span></p><p>Следующие $$$m$$$ строк описывают поезда. $$$i$$$-я из этих строк содержит два целых числа $$$s_i,t_i$$$ ($$$1\le s_i\le n$$$, $$$1\le t_1&lt;t_2&lt;\cdots&lt;t_m\le 10^9$$$) — станция назначения и время, в которое $$$i$$$-й поезд прибудет на станцию $$$1$$$, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа: наибольшее возможное время первого взрыва (или $$$-1$$$, если можно предотвратить взрывы) и минимальное количество переключений, необходимое, чтобы достичь этого.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 1 2 1 1 3 2 3 4 1 3 5 3 2 1 4 2 2 6 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 1 2 1 1 3 2 3 4 1 3 5 3 5 1 4 2 4 3 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 11 6 1 2 1 1 3 2 3 4 1 3 5 2 5 6 1 5 7 2 7 8 1 7 9 2 9 10 1 9 11 1 2 1 8 3 6 5 10 7 4 9 2 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте один из возможных примеров того, как все будет происходить, описан ниже. </p><ul> <li> В момент времени $$$1$$$ поезд $$$1$$$ прибывает на станцию $$$1$$$. Переключатель станции $$$1$$$ направлен к станции $$$2$$$. Поезд $$$1$$$ отправляется к станции $$$2$$$. </li><li> В момент времени $$$2$$$ поезд $$$2$$$ прибывает на станцию $$$1$$$ и поезд $$$1$$$ прибывает на станцию $$$2$$$, где останавливается навсегда. Мы переключаем переключатель в станции $$$1$$$ к станции $$$3$$$. Поезд $$$2$$$ направляется к станции $$$3$$$. </li><li> В момент времени $$$4$$$ поезд $$$2$$$ прибывает на станцию $$$3$$$. Мы переключаем переключатель в станции $$$3$$$ к станции $$$4$$$. Поезд $$$2$$$ направляется к станции $$$4$$$. </li><li> В момент времени $$$5$$$ поезд $$$2$$$ прибывает на станцию $$$4$$$, где останавливается навсегда. </li><li> В момент времени $$$6$$$ поезд $$$3$$$ прибывает на станцию $$$1$$$. Мы переключаем переключатель станции $$$1$$$ к станции $$$2$$$. Поезд $$$3$$$ направляется к станции $$$2$$$. </li><li> В момент времени $$$7$$$ поезд $$$3$$$ прибывает на станцию $$$2$$$, где останавливается навсегда. Мы переключаем переключатель станции $$$3$$$ к станции $$$5$$$. </li><li> В момент времени $$$10$$$ поезд $$$4$$$ прибывает на станцию $$$1$$$. Мы переключаем переключатель станции $$$1$$$ к станции $$$3$$$. Поезд $$$4$$$ направляется к станции $$$3$$$. </li><li> В момент времени $$$12$$$ поезд $$$4$$$ прибывает на станцию $$$3$$$. Поезд $$$4$$$ направляется к станции $$$5$$$. </li><li> В момент времени $$$15$$$ поезд $$$4$$$ прибывает на станцию $$$5$$$, где останавливается навсегда. </li></ul><p>Во втором тесте мы не переключаем ничего. В момент времени $$$4$$$ поезд $$$2$$$ направляется к станции $$$5$$$, и поезд $$$4$$$ направляется к станции $$$3$$$. Они оба взрываются. Невозможно предотвратить взрывы поездов к моменту времени $$$4$$$.</p><p>В третьем тесте давайте будем обозначать переключение переключателя как $$$(u\to v,t)$$$, если мы переключаем переключатель станции $$$u$$$ к станции $$$v$$$ в момент времени $$$t$$$. Одним из решений является сделать следующие $$$4$$$ переключения: $$$(1\to 2,1)$$$, $$$(1\to 3,2)$$$, $$$(7\to 8,5)$$$, $$$(5\to 6,8)$$$. В момент времени $$$11$$$ поезда $$$4$$$, $$$5$$$ и $$$6$$$ взорвутся. Невозможно предотвратить взрывы поездов к моменту времени $$$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 11:02: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:'81249f4dfa2215fe',t:'MTY5NjY2NTc1MS4wMTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3100"]
1344F
1344
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><span class="tex-font-style-it">Пит Мондриан — художник, наиболее известный своими минималистскими работами, состоящими только из четырех цветов: красного, желтого, синего и белого. Большинство людей объясняют это его стилем, но правда заключается в том, что смешивание двух его основных цветов лишь создает другой основной цвет!</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3af3793868336bdf970c98194b7c689683d0dd31.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-style-it">Менее известное произведение, названное «Претенциозные прямоугольники»</span> </center><p>Последовательность из нескольких основных цветов (красного, желтого и синего) смешивается следующим образом: пока есть хотя бы два цвета, посмотрим на первые два. Если они разные, заменим их на недостающий в этой паре цвет. Если они одинаковые, удалим их из последовательности. В конце, если в последовательности есть один цвет, этот цвет будет результатом смешивания. Иначе, если последовательность пустая, результатом смешивания будет белый. Рассмотрим два примера смешивания последовательности цветов:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/948530fff451cb13e7e5c7a247351601acf3142e.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center>   <center> <img class="tex-graphics" src="https://espresso.codeforces.com/bca3db1e6223b5454e68e2faab650409a69b97bc.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>У Пита есть цветная палитра, состоящая из нескольких клеток, пронумерованых от $$$1$$$ до $$$n$$$. Каждая клетка пустая или содержит один из основных цветов. Пит очень секретный и не покажет вам свою палитру, поэтому вы не знаете, какие цвета находятся в каждой клетке.</p><p>Несмотря на это, художник выполнил $$$k$$$ операций. Всего есть четыре вида операций: </p><ol> <li> Операция <span class="tex-font-style-bf">mix</span>: Пит выбирает подмножество клеток и смешивает цвета в выбранных клетках в некотором порядке (не обязательно по возрастанию индексов). Он записывает получившийся цвет. Пустые клетки не влияют на процесс смешивания и игнорируются. Смешивание не влияет на цвета в клетках палитры. </li><li> Операция <span class="tex-font-style-bf">RY</span>: Пит выбирает подмножество клеток. Каждая красная клетка в этом подмножестве становится желтой, и каждая желтая клетка в этом подмножестве становится красной. Синие и пустые клетки не меняют свой цвет. </li><li> Операция <span class="tex-font-style-bf">RB</span>: Пит выбирает подмножество клеток. Каждая красная клетка в этом подмножестве становится синей, и каждая синяя клетка в этом подмножестве становится красной. Желтые и пустые клетки не меняют свой цвет. </li><li> Операция <span class="tex-font-style-bf">YB</span>: Пит выбирает подмножество клеток. Каждая желтая клетка в этом подмножестве становится синей, и каждая синяя клетка в этом подмножестве становится желтой. Красные и пустые клетки не меняют свой цвет. </li></ol><p>Пит сказал вам список операций, которые он выполнил, в хронологическом порядке, с соответствующими индексами и результатами каждой операции <span class="tex-font-style-tt">mix</span>. Имея эту информацию, определите цвет каждой клетки в изначальной палитре. Вы должны найти одно из возможных состояний изначальной палитры (до применения операций) или сказать, что описанная ситуация невозможна.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$k$$$ ($$$1\le n,k\le 1000$$$) — количество клеток в палитре и количество операций соответственно.</p><p>Следующие $$$k$$$ строк описывают операции. $$$i$$$-я из этих строк начинается с названия $$$i$$$-й операции и целого числа $$$m$$$ ($$$1\le m\le n$$$) — количества использованных в операции индексов. Затем следуют $$$m$$$ целых чисел $$$j_1,\ldots,j_m$$$ ($$$1\le j_i\le n$$$) — индексы клеток, выбранных в операции. Гарантируется, что в каждой операции все $$$j_i$$$ различны. Если это операция <span class="tex-font-style-tt">mix</span>, индексы перечисляются в том порядке, в котором цвета смешиваются, и в конце строки также дается один символ, означающий получившийся в результате смешивания цвет: «<span class="tex-font-style-tt">R</span>» для красного, «<span class="tex-font-style-tt">Y</span>» для желтого, «<span class="tex-font-style-tt">B</span>» для синего и «<span class="tex-font-style-tt">W</span>» для белого.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите «<span class="tex-font-style-tt">YES</span>», если решение существует, и «<span class="tex-font-style-tt">NO</span>» иначе. Вы можете выводить каждый символ в любом регистре (верхнем или нижнем).</p><p>Если ответ «<span class="tex-font-style-tt">YES</span>», в следующей строке выведите строку длины $$$n$$$, состоящую из символов «<span class="tex-font-style-tt">R</span>», «<span class="tex-font-style-tt">Y</span>», «<span class="tex-font-style-tt">B</span>» или «<span class="tex-font-style-tt">.</span>», задающую цвета $$$n$$$ клеток на изначальной палитре (красный, желтый, синий цвета и пустая клетка соответственно). Если есть несколько возможных изначальных палитр, выведите любую. Вы можете выводить каждый символ в любом регистре (верхнем или нижнем).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 mix 2 2 1 R mix 2 1 3 Y </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YB. </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 3 mix 1 2 Y RB 1 2 mix 1 2 W </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 3 RY 1 1 YB 1 1 mix 1 1 B </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES R </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 8 mix 2 1 2 R mix 2 1 3 Y RY 2 2 3 RB 3 1 2 3 YB 3 1 2 3 mix 1 1 W mix 1 2 B mix 1 3 Y </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES .RY </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте ответ «<span class="tex-font-style-tt">YB.</span>» не противоречит обоим смешиваниям. При первом смешивании последовательности цветов «<span class="tex-font-style-tt">BY</span>» получится красный цвет, при втором смешивании последовательности цветов «<span class="tex-font-style-tt">Y</span>» получится желтый цвет (пустые клетки игнорируются). Некоторые другие возможные ответы: «<span class="tex-font-style-tt">BYR</span>» и «<span class="tex-font-style-tt">.RY</span>».</p><p>Во втором тесте можно показать, что не существует ни одной не противоречивой расстановки цветов на изначальной палитре.</p><p>В третьем тесте ответ «<span class="tex-font-style-tt">R</span>» не противоречит никаким операциям. В первой операции палитра меняется на «<span class="tex-font-style-tt">Y</span>», затем на «<span class="tex-font-style-tt">B</span>». В последней операции при смешивании последовательности цветов «<span class="tex-font-style-tt">B</span>» получается синий цвет.</p><p>В четвертом тесте ответ «<span class="tex-font-style-tt">.RY</span>» не противоречит никаким операциям. В первых двух смешиваниях последовательности цветов «<span class="tex-font-style-tt">R</span>» и «<span class="tex-font-style-tt">Y</span>» смешиваются в красный и желтый цвета соответственно. В следующих трех операциях палитра изменяется на «<span class="tex-font-style-tt">.YR</span>», затем на «<span class="tex-font-style-tt">.YB</span>», затем на «<span class="tex-font-style-tt">.BY</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="e6e1b66fc62128f5988b9e324ba714b1"/> <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="984a23f77a0946e4a43d943727943ad0eb00b4aa"/> <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='e6e1b66fc62128f5988b9e324ba714b1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1344%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='e6e1b66fc62128f5988b9e324ba714b1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1344">Codeforces Round 639 (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='e6e1b66fc62128f5988b9e324ba714b1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1344/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Произведение матриц, определитель, правило Крамера, системы линейных уравнений"> матрицы </span> </div> <div class="roundbox borderTopRound 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='e6e1b66fc62128f5988b9e324ba714b1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600705"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e6e1b66fc62128f5988b9e324ba714b1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600705"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10843" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10856" resourceName="Codeforces Round #639 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/1344">Задачи</a></li> <li><a href="/contest/1344/submit">Отослать</a></li> <li><a href="/contest/1344/my">Мои посылки</a></li> <li><a href="/contest/1344/status">Статус</a></li> <li><a href="/contest/1344/hacks">Взломы</a></li> <li><a href="/contest/1344/room/1">Комната</a></li> <li><a href="/contest/1344/standings">Положение</a></li> <li><a href="/contest/1344/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a63dd0dcf660841508f5c93f3733fa32b8763624"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><span class="tex-font-style-it">Пит Мондриан — художник, наиболее известный своими минималистскими работами, состоящими только из четырех цветов: красного, желтого, синего и белого. Большинство людей объясняют это его стилем, но правда заключается в том, что смешивание двух его основных цветов лишь создает другой основной цвет!</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3af3793868336bdf970c98194b7c689683d0dd31.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-style-it">Менее известное произведение, названное «Претенциозные прямоугольники»</span> </center><p>Последовательность из нескольких основных цветов (красного, желтого и синего) смешивается следующим образом: пока есть хотя бы два цвета, посмотрим на первые два. Если они разные, заменим их на недостающий в этой паре цвет. Если они одинаковые, удалим их из последовательности. В конце, если в последовательности есть один цвет, этот цвет будет результатом смешивания. Иначе, если последовательность пустая, результатом смешивания будет белый. Рассмотрим два примера смешивания последовательности цветов:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/948530fff451cb13e7e5c7a247351601acf3142e.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center>   <center> <img class="tex-graphics" src="https://espresso.codeforces.com/bca3db1e6223b5454e68e2faab650409a69b97bc.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>У Пита есть цветная палитра, состоящая из нескольких клеток, пронумерованых от $$$1$$$ до $$$n$$$. Каждая клетка пустая или содержит один из основных цветов. Пит очень секретный и не покажет вам свою палитру, поэтому вы не знаете, какие цвета находятся в каждой клетке.</p><p>Несмотря на это, художник выполнил $$$k$$$ операций. Всего есть четыре вида операций: </p><ol> <li> Операция <span class="tex-font-style-bf">mix</span>: Пит выбирает подмножество клеток и смешивает цвета в выбранных клетках в некотором порядке (не обязательно по возрастанию индексов). Он записывает получившийся цвет. Пустые клетки не влияют на процесс смешивания и игнорируются. Смешивание не влияет на цвета в клетках палитры. </li><li> Операция <span class="tex-font-style-bf">RY</span>: Пит выбирает подмножество клеток. Каждая красная клетка в этом подмножестве становится желтой, и каждая желтая клетка в этом подмножестве становится красной. Синие и пустые клетки не меняют свой цвет. </li><li> Операция <span class="tex-font-style-bf">RB</span>: Пит выбирает подмножество клеток. Каждая красная клетка в этом подмножестве становится синей, и каждая синяя клетка в этом подмножестве становится красной. Желтые и пустые клетки не меняют свой цвет. </li><li> Операция <span class="tex-font-style-bf">YB</span>: Пит выбирает подмножество клеток. Каждая желтая клетка в этом подмножестве становится синей, и каждая синяя клетка в этом подмножестве становится желтой. Красные и пустые клетки не меняют свой цвет. </li></ol><p>Пит сказал вам список операций, которые он выполнил, в хронологическом порядке, с соответствующими индексами и результатами каждой операции <span class="tex-font-style-tt">mix</span>. Имея эту информацию, определите цвет каждой клетки в изначальной палитре. Вы должны найти одно из возможных состояний изначальной палитры (до применения операций) или сказать, что описанная ситуация невозможна.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$k$$$ ($$$1\le n,k\le 1000$$$) — количество клеток в палитре и количество операций соответственно.</p><p>Следующие $$$k$$$ строк описывают операции. $$$i$$$-я из этих строк начинается с названия $$$i$$$-й операции и целого числа $$$m$$$ ($$$1\le m\le n$$$) — количества использованных в операции индексов. Затем следуют $$$m$$$ целых чисел $$$j_1,\ldots,j_m$$$ ($$$1\le j_i\le n$$$) — индексы клеток, выбранных в операции. Гарантируется, что в каждой операции все $$$j_i$$$ различны. Если это операция <span class="tex-font-style-tt">mix</span>, индексы перечисляются в том порядке, в котором цвета смешиваются, и в конце строки также дается один символ, означающий получившийся в результате смешивания цвет: «<span class="tex-font-style-tt">R</span>» для красного, «<span class="tex-font-style-tt">Y</span>» для желтого, «<span class="tex-font-style-tt">B</span>» для синего и «<span class="tex-font-style-tt">W</span>» для белого.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите «<span class="tex-font-style-tt">YES</span>», если решение существует, и «<span class="tex-font-style-tt">NO</span>» иначе. Вы можете выводить каждый символ в любом регистре (верхнем или нижнем).</p><p>Если ответ «<span class="tex-font-style-tt">YES</span>», в следующей строке выведите строку длины $$$n$$$, состоящую из символов «<span class="tex-font-style-tt">R</span>», «<span class="tex-font-style-tt">Y</span>», «<span class="tex-font-style-tt">B</span>» или «<span class="tex-font-style-tt">.</span>», задающую цвета $$$n$$$ клеток на изначальной палитре (красный, желтый, синий цвета и пустая клетка соответственно). Если есть несколько возможных изначальных палитр, выведите любую. Вы можете выводить каждый символ в любом регистре (верхнем или нижнем).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 mix 2 2 1 R mix 2 1 3 Y </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YB. </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 3 mix 1 2 Y RB 1 2 mix 1 2 W </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 3 RY 1 1 YB 1 1 mix 1 1 B </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES R </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 8 mix 2 1 2 R mix 2 1 3 Y RY 2 2 3 RB 3 1 2 3 YB 3 1 2 3 mix 1 1 W mix 1 2 B mix 1 3 Y </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES .RY </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте ответ «<span class="tex-font-style-tt">YB.</span>» не противоречит обоим смешиваниям. При первом смешивании последовательности цветов «<span class="tex-font-style-tt">BY</span>» получится красный цвет, при втором смешивании последовательности цветов «<span class="tex-font-style-tt">Y</span>» получится желтый цвет (пустые клетки игнорируются). Некоторые другие возможные ответы: «<span class="tex-font-style-tt">BYR</span>» и «<span class="tex-font-style-tt">.RY</span>».</p><p>Во втором тесте можно показать, что не существует ни одной не противоречивой расстановки цветов на изначальной палитре.</p><p>В третьем тесте ответ «<span class="tex-font-style-tt">R</span>» не противоречит никаким операциям. В первой операции палитра меняется на «<span class="tex-font-style-tt">Y</span>», затем на «<span class="tex-font-style-tt">B</span>». В последней операции при смешивании последовательности цветов «<span class="tex-font-style-tt">B</span>» получается синий цвет.</p><p>В четвертом тесте ответ «<span class="tex-font-style-tt">.RY</span>» не противоречит никаким операциям. В первых двух смешиваниях последовательности цветов «<span class="tex-font-style-tt">R</span>» и «<span class="tex-font-style-tt">Y</span>» смешиваются в красный и желтый цвета соответственно. В следующих трех операциях палитра изменяется на «<span class="tex-font-style-tt">.YR</span>», затем на «<span class="tex-font-style-tt">.YB</span>», затем на «<span class="tex-font-style-tt">.BY</span>». Последние три смешивания согласуются с получившейся палитрой.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:02: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:'81249f577d1b9d3a',t:'MTY5NjY2NTc1Mi4zODcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "*3200"]
1345A
1345
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\cdot m$$$ одинаковых деталей. Каждая деталь имеет три выступа и одну выемку, как показано на рисунке.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/12bd9722a46824150283fab59ae3dad3c2926ed9.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Пазл считается собранным, если следующие условия выполнены:</p><ol> <li> Детали расположены в виде прямоугольника с $$$n$$$ строками и $$$m$$$ столбцами. </li><li> Любые две детали, которые имеют общую сторону в прямоугольнике, идеально соединяются с помощью выступа одной детали и выемки другой. </li></ol><p>Определите, можно ли собрать пазл, вращая и перемещая детали как угодно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько тестовых случаев. В первой строке находится единственное целое число $$$t$$$ ($$$1\le t\le 1000$$$) — количество тестовых случаев. В следующих $$$t$$$ строках следует описание тестовых случаев.</p><p>Единственная строка описания каждого тестового случая содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n,m \le 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> 3 1 3 100000 100000 2 2 </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><center> <img class="tex-graphics" src="https://espresso.codeforces.com/03f246790d1b31b27745f0ae94fc105e94373d46.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Для второго тестового случая можно показать, что пазл собрать невозможно.</p><p>В третьем тестовом случае один из возможных примеров решения пазла:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b09e8310c88f18ac6bfa5ec4b17f92aa50d890bb.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="ed7996dd6ecacc48dcc9014b27efca07"/> <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="fc28f014ca80adf5f290c143b1f2317a08e23c98"/> <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='ed7996dd6ecacc48dcc9014b27efca07'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1345%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='ed7996dd6ecacc48dcc9014b27efca07'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1345">Codeforces Round 639 (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='ed7996dd6ecacc48dcc9014b27efca07'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1345/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='ed7996dd6ecacc48dcc9014b27efca07'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600707"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ed7996dd6ecacc48dcc9014b27efca07'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600707"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10844" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10857" resourceName="Codeforces Round #639 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/1345">Задачи</a></li> <li><a href="/contest/1345/submit">Отослать</a></li> <li><a href="/contest/1345/my">Мои посылки</a></li> <li><a href="/contest/1345/status">Статус</a></li> <li><a href="/contest/1345/hacks">Взломы</a></li> <li><a href="/contest/1345/room/1">Комната</a></li> <li><a href="/contest/1345/standings">Положение</a></li> <li><a href="/contest/1345/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2e86a00fdcb3f43640e06244e031d105786ec9e5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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\cdot m$$$ одинаковых деталей. Каждая деталь имеет три выступа и одну выемку, как показано на рисунке.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/12bd9722a46824150283fab59ae3dad3c2926ed9.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Пазл считается собранным, если следующие условия выполнены:</p><ol> <li> Детали расположены в виде прямоугольника с $$$n$$$ строками и $$$m$$$ столбцами. </li><li> Любые две детали, которые имеют общую сторону в прямоугольнике, идеально соединяются с помощью выступа одной детали и выемки другой. </li></ol><p>Определите, можно ли собрать пазл, вращая и перемещая детали как угодно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько тестовых случаев. В первой строке находится единственное целое число $$$t$$$ ($$$1\le t\le 1000$$$) — количество тестовых случаев. В следующих $$$t$$$ строках следует описание тестовых случаев.</p><p>Единственная строка описания каждого тестового случая содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n,m \le 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> 3 1 3 100000 100000 2 2 </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><center> <img class="tex-graphics" src="https://espresso.codeforces.com/03f246790d1b31b27745f0ae94fc105e94373d46.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Для второго тестового случая можно показать, что пазл собрать невозможно.</p><p>В третьем тестовом случае один из возможных примеров решения пазла:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b09e8310c88f18ac6bfa5ec4b17f92aa50d890bb.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'81249f600d520058',t:'MTY5NjY2NTc1Ny4wMzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1345B
1345
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$$$ может быть построена с помощью двух карт, приставленных друг к другу. Для $$$h&gt;1$$$ карточная пирамида высоты $$$h$$$ может быть построена расположением карточной пирамиды высоты $$$h-1$$$ на базе. База состоит из $$$h$$$ пирамидок высоты $$$1$$$, поставленных в ряд, и $$$h-1$$$ карты, лежащей сверху на них. Например, карточные пирамиды с высотами $$$1$$$, $$$2$$$ и $$$3$$$ выглядят следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/03d27fa5105a849bb8363e064d735c2d4240187a.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Изначально у вас есть $$$n$$$ карт и вы строите как можно более высокую пирамиду из этих карт. Если остались лишние карты, вы снова строите как можно более высокую пирамиду из оставшихся карт. Вы продолжаете этот процесс до тих пор, пока не станет невозможно построить какую-нибудь пирамиду. Сколько карточных пирамид вы построите?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких тестовых случаев. Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t\le 1000$$$) — количество тестовых случаев. Следующие $$$t$$$ строк содержат описания тестовых случаев.</p><p>Единственная строка описания каждого тестового случая содержит единственное целое число $$$n$$$ ($$$1\le n\le 10^9$$$) — количество карт.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превосходит $$$10^9$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите единственное целое число — количество карточных пирамид, которое вы построите в конце процесса.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 14 15 24 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 3 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае вы построите карточную пирамиду высоты $$$1$$$ из $$$2$$$-x карт. Останется $$$1$$$ карта, которой недостаточно, чтобы построить какую-нибудь пирамиду.</p><p>Во втором тестовом случае вы построите две пирамиды, каждая высоты $$$2$$$, и в конце процесса не останется карт.</p><p>В третьем тестовом случае вы построите одну пирамиду высоты $$$3$$$, и ни одной карты не останется.</p><p>В четвертом тестовом случае вы сначала построите одну пирамиду высоты $$$3$$$, и $$$9$$$ карт останется. Затем вы построите пирамиду высоты $$$2$$$, и $$$2$$$ карты останется. Наконец, вы построите последнюю пирамиду высоты $$$1$$$, и не останется ни одной карты.</p><p>В пятом тестовом случае одной карты недостаточно, чтобы построить какую-нибудь пирамиду.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="cc077406bd21050cde1c50be8607274a"/> <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="fc28f014ca80adf5f290c143b1f2317a08e23c98"/> <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='cc077406bd21050cde1c50be8607274a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1345%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='cc077406bd21050cde1c50be8607274a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1345">Codeforces Round 639 (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='cc077406bd21050cde1c50be8607274a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1345/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='cc077406bd21050cde1c50be8607274a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600708"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cc077406bd21050cde1c50be8607274a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600708"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10844" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10857" resourceName="Codeforces Round #639 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/1345">Задачи</a></li> <li><a href="/contest/1345/submit">Отослать</a></li> <li><a href="/contest/1345/my">Мои посылки</a></li> <li><a href="/contest/1345/status">Статус</a></li> <li><a href="/contest/1345/hacks">Взломы</a></li> <li><a href="/contest/1345/room/1">Комната</a></li> <li><a href="/contest/1345/standings">Положение</a></li> <li><a href="/contest/1345/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6bcffbd7ee226bbc84022064cacfe43acecc1fd7"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ может быть построена с помощью двух карт, приставленных друг к другу. Для $$$h&gt;1$$$ карточная пирамида высоты $$$h$$$ может быть построена расположением карточной пирамиды высоты $$$h-1$$$ на базе. База состоит из $$$h$$$ пирамидок высоты $$$1$$$, поставленных в ряд, и $$$h-1$$$ карты, лежащей сверху на них. Например, карточные пирамиды с высотами $$$1$$$, $$$2$$$ и $$$3$$$ выглядят следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/03d27fa5105a849bb8363e064d735c2d4240187a.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Изначально у вас есть $$$n$$$ карт и вы строите как можно более высокую пирамиду из этих карт. Если остались лишние карты, вы снова строите как можно более высокую пирамиду из оставшихся карт. Вы продолжаете этот процесс до тих пор, пока не станет невозможно построить какую-нибудь пирамиду. Сколько карточных пирамид вы построите?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких тестовых случаев. Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t\le 1000$$$) — количество тестовых случаев. Следующие $$$t$$$ строк содержат описания тестовых случаев.</p><p>Единственная строка описания каждого тестового случая содержит единственное целое число $$$n$$$ ($$$1\le n\le 10^9$$$) — количество карт.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем тестовым случаям не превосходит $$$10^9$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите единственное целое число — количество карточных пирамид, которое вы построите в конце процесса.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 14 15 24 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 3 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае вы построите карточную пирамиду высоты $$$1$$$ из $$$2$$$-x карт. Останется $$$1$$$ карта, которой недостаточно, чтобы построить какую-нибудь пирамиду.</p><p>Во втором тестовом случае вы построите две пирамиды, каждая высоты $$$2$$$, и в конце процесса не останется карт.</p><p>В третьем тестовом случае вы построите одну пирамиду высоты $$$3$$$, и ни одной карты не останется.</p><p>В четвертом тестовом случае вы сначала построите одну пирамиду высоты $$$3$$$, и $$$9$$$ карт останется. Затем вы построите пирамиду высоты $$$2$$$, и $$$2$$$ карты останется. Наконец, вы построите последнюю пирамиду высоты $$$1$$$, и не останется ни одной карты.</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 11:02: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:'81249f7d394f1622',t:'MTY5NjY2NTc1OC41MjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1100"]
1345C
1345
C
ru
C. Отель Гильберта
<div class="problem-statement"><div class="header"><div class="title">C. Отель Гильберта</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Отель Гильберта это очень необычный отель, потому что количество комнат в нем бесконечно! Для каждого целого числа существует ровно одна комната с таким номером, <span class="tex-font-style-bf">включая ноль и отрицательные числа</span>. Не менее странно то, что сейчас отель полностью заполнен, что означает, что в каждой комнате находится ровно один гость. Менеджер отеля, сам Давид Гильберт, решил переместить гостей, потому что у него есть предположение, что за счет этого образуются свободные места.</p><p>Для любого целого числа $$$k$$$ и положительного целого числа $$$n$$$ обозначим за $$$k\bmod n$$$ остаток при делении числа $$$k$$$ на число $$$n$$$. Более формально, $$$r=k\bmod n$$$ это наименьшее неотрицательное целое число такое, что $$$k-r$$$ делится на $$$n$$$. Всегда выполнено, что $$$0\le k\bmod n\le n-1$$$. Например, $$$100\bmod 12=4$$$ и $$$(-1337)\bmod 3=1$$$.</p><p>Процесс перемещения гостей выглядит следующим образом: есть массив, состоящий из $$$n$$$ целых чисел $$$a_0,a_1,\ldots,a_{n-1}$$$. Тогда для всех целых чисел $$$k$$$ гость из комнаты с номером $$$k$$$ перемещается в комнату с номером $$$k+a_{k\bmod n}$$$.</p><p>Определите, верно ли, что после этого процесса перемещения в каждой комнате по-прежнему находится ровно один гость. Это означает, что нет пустых комнат и комнат, в которых больше одного гостя.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких тестовых случаев. Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество тестовых случаев. Следующие $$$2t$$$ строк содержат описания тестовых случаев.</p><p>В первой строке описания каждого тестового случая находится единственное целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — длина массива.</p><p>Во второй строке описания каждого тестового случая находятся $$$n$$$ целых чисел $$$a_0,a_1,\ldots,a_{n-1}$$$ ($$$-10^9\le a_i\le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите единственную строку, содержащую «<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 1 14 2 1 -1 4 5 5 5 1 3 3 2 1 2 0 1 5 -239 -2 -100 -3 -11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES NO NO YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае номер комнаты каждого гостя увеличился на $$$14$$$, поэтому по-прежнему в каждой комнате находится ровно один гость.</p><p>Во втором тестовом случае гости в комнатах с четными номерами перемещаются в комнату с номером, на $$$1$$$ большим исходного; гости в комнатах с нечетными номерами перемещаются в комнату с номером, на $$$1$$$ меньшим исходного. Можно показать, что по-прежнему в каждой комнате находится ровно один гость.</p><p>В третьем тестовом случае каждый четвертый гость перемещается в комнату с номером, на $$$1$$$ большим исходного, а остальные гости перемещаются в комнату с номером, на $$$5$$$ большим. Можно показать, что по-прежнему в каждой комнате находится ровно один гость.</p><p>В четвертом тестовом случае гости, исходно находящиеся в комнатах $$$0$$$ и $$$1$$$, перемещаются в комнату с номером $$$3$$$.</p><p>В пятом тестовом случае гости, находящиеся в комнатах $$$1$$$ и $$$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="f4e8941120f485db3c0a342b79ce52e2"/> <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="fc28f014ca80adf5f290c143b1f2317a08e23c98"/> <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='f4e8941120f485db3c0a342b79ce52e2'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1345%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='f4e8941120f485db3c0a342b79ce52e2'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1345">Codeforces Round 639 (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='f4e8941120f485db3c0a342b79ce52e2'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1345/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='f4e8941120f485db3c0a342b79ce52e2'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600709"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f4e8941120f485db3c0a342b79ce52e2'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600709"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10844" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10857" resourceName="Codeforces Round #639 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/1345">Задачи</a></li> <li><a href="/contest/1345/submit">Отослать</a></li> <li><a href="/contest/1345/my">Мои посылки</a></li> <li><a href="/contest/1345/status">Статус</a></li> <li><a href="/contest/1345/hacks">Взломы</a></li> <li><a href="/contest/1345/room/1">Комната</a></li> <li><a href="/contest/1345/standings">Положение</a></li> <li><a href="/contest/1345/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4c7b174e3007f611db3d0aa00f78034eac196dfe"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Отель Гильберта</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Отель Гильберта это очень необычный отель, потому что количество комнат в нем бесконечно! Для каждого целого числа существует ровно одна комната с таким номером, <span class="tex-font-style-bf">включая ноль и отрицательные числа</span>. Не менее странно то, что сейчас отель полностью заполнен, что означает, что в каждой комнате находится ровно один гость. Менеджер отеля, сам Давид Гильберт, решил переместить гостей, потому что у него есть предположение, что за счет этого образуются свободные места.</p><p>Для любого целого числа $$$k$$$ и положительного целого числа $$$n$$$ обозначим за $$$k\bmod n$$$ остаток при делении числа $$$k$$$ на число $$$n$$$. Более формально, $$$r=k\bmod n$$$ это наименьшее неотрицательное целое число такое, что $$$k-r$$$ делится на $$$n$$$. Всегда выполнено, что $$$0\le k\bmod n\le n-1$$$. Например, $$$100\bmod 12=4$$$ и $$$(-1337)\bmod 3=1$$$.</p><p>Процесс перемещения гостей выглядит следующим образом: есть массив, состоящий из $$$n$$$ целых чисел $$$a_0,a_1,\ldots,a_{n-1}$$$. Тогда для всех целых чисел $$$k$$$ гость из комнаты с номером $$$k$$$ перемещается в комнату с номером $$$k+a_{k\bmod n}$$$.</p><p>Определите, верно ли, что после этого процесса перемещения в каждой комнате по-прежнему находится ровно один гость. Это означает, что нет пустых комнат и комнат, в которых больше одного гостя.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких тестовых случаев. Первая строка содержит единственное целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество тестовых случаев. Следующие $$$2t$$$ строк содержат описания тестовых случаев.</p><p>В первой строке описания каждого тестового случая находится единственное целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — длина массива.</p><p>Во второй строке описания каждого тестового случая находятся $$$n$$$ целых чисел $$$a_0,a_1,\ldots,a_{n-1}$$$ ($$$-10^9\le a_i\le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите единственную строку, содержащую «<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 1 14 2 1 -1 4 5 5 5 1 3 3 2 1 2 0 1 5 -239 -2 -100 -3 -11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES NO NO YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае номер комнаты каждого гостя увеличился на $$$14$$$, поэтому по-прежнему в каждой комнате находится ровно один гость.</p><p>Во втором тестовом случае гости в комнатах с четными номерами перемещаются в комнату с номером, на $$$1$$$ большим исходного; гости в комнатах с нечетными номерами перемещаются в комнату с номером, на $$$1$$$ меньшим исходного. Можно показать, что по-прежнему в каждой комнате находится ровно один гость.</p><p>В третьем тестовом случае каждый четвертый гость перемещается в комнату с номером, на $$$1$$$ большим исходного, а остальные гости перемещаются в комнату с номером, на $$$5$$$ большим. Можно показать, что по-прежнему в каждой комнате находится ровно один гость.</p><p>В четвертом тестовом случае гости, исходно находящиеся в комнатах $$$0$$$ и $$$1$$$, перемещаются в комнату с номером $$$3$$$.</p><p>В пятом тестовом случае гости, находящиеся в комнатах $$$1$$$ и $$$2$$$, перемещаются в комнату с номером $$$2$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:02: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:'81249f868c945aae',t:'MTY5NjY2NTc1OS44MjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1600"]
1345D
1345
D
ru
D. Однополюсные магниты
<div class="problem-statement"><div class="header"><div class="title">D. Однополюсные магниты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Однополюсный магнит — это магнит, у которого ровно один полюс: либо северный, либо южный. Они не существуют в природе, потому что настоящие магниты имеют два полюса, но это задача по программированию, поэтому будем считать, что такие магниты существуют.</p><p>У вас есть таблица размером $$$n\times m$$$. Изначально вы можете поставить несколько магнитов с северным полюсом и несколько магнитов с южным полюсом в некоторые клетки этой таблицы. Вам разрешено расставлять сколько угодно магнитов, в том числе несколько в одну клетку.</p><p>Можно выполнять следующую операцию: выбрать один магнит с северным полюсом и один магнит с южным полюсом для активации. Если они находятся в одной строке или в одном столбце, но занимают разные клетки, то магнит с северным полюсом переместится на одну клетку ближе к магниту с южным полюсом. Иначе, если они занимают одинаковые клетки или не находятся в одной строке или в одном столбце, то ничего не произойдет. Обратите внимание, что магниты с южным полюсом неподвижны.</p><p>Каждая клетка таблицы покрашена в черный или белый цвет. Будем рассматривать расстановки магнитов в таблице, для которых следующие условия будут выполнены.</p><ol> <li> В каждой строке и каждом столбце таблицы находится хотя бы один магнит с южным полюсом. </li><li> Если клетка таблицы черная, тогда можно переместить какой-нибудь магнит с северным полюсом в эту клетку с помощью некоторой последовательности операций <span class="tex-font-style-bf">из начального расположения магнитов</span>. </li><li> Если клетка таблицы белая, тогда никакой магнит с северным полюсом невозможно переместить в эту клетку с помощью некоторой последовательности операций <span class="tex-font-style-bf">из начального расположения магнитов</span>. </li></ol><p>Определите, можно ли расположить магниты в таблице так, что все условия будут выполнены. Если это возможно, найдите минимальное количество магнитов с северным полюсом, которое для этого требуется (минимизировать количество магнитов с южным полюсом не нужно).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$1\le n,m\le 1000$$$)  — количество строк и столбцов в таблице, соответственно.</p><p>Следующие $$$n$$$ строк описывают раскраску таблицы: $$$i$$$-я из этих строк содержит строку длины $$$m$$$, в которой $$$j$$$-й символ обозначает цвет клетки таблицы, находящейся в строке $$$i$$$ и столбце $$$j$$$. Символы «<span class="tex-font-style-tt">#</span>» и «<span class="tex-font-style-tt">.</span>» обозначают черный и белый цвета соответственно. Гарантируется, что строка не содержит других символов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число, которое равно минимальному количеству магнитов с северным полюсом, которое требуется.</p><p>Если не существует способа расставить магниты, который будет удовлетворять всем условиям, выведите единственное целое число $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 .#. ### ##. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 ## .# .# ## </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 ....# ####. .###. .#... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 . # </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 ..... ..... ..... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте возможно расположить магниты следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f89d8c7a378384a96c7e162b53499c211fbb21cd.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором тесте можно показать, что не существует необходимых расположений магнитов. На следующей картинке показаны три примера расположений, которые удовлетворяют не всем условиям. Первый пример нарушает правило $$$3$$$, потому что мы можем переместить магнит с северным полюсом вниз на белую клетку. Второй пример нарушает правило $$$2$$$, потому что мы не можем переместить магнит с северным полюсом в левую нижнюю черную клетку никакой последовательностью операций. Третий пример нарушает правило $$$1$$$, потому что нет ни одного магнита с южным полюсом в первом столбце.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4bf25d94e49a452e00895f940f4e76d26d8cde35.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Следующая картинка показывает пример возможного расположения магнитов в третьем тесте. Можно показать, что не существует необходимых расположений магнитов с меньшим количеством магнитов с северным полюсом.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/730abcba1dab5abea574d5f479fe54cdf3f528ae.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во четвертом тесте можно показать, что не существует необходимых расположений магнитов. На следующей картинке два примера расположений, которые удовлетворяют не всем условиям. Первый пример нарушает правило $$$1$$$, потому что нет ни одного магнита с южным полюсом в первой строке. Второй пример нарушает правила $$$1$$$ и $$$3$$$, потому что нет ни одного магнита с южным полюсом во второй строке, а кроме того, мы можем переместить магнит с северным полюсом на одну клетку вверх, и он попадет на белую клетку.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c719c90077972d8befc8234a02d55b35d7736299.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В пятом тесте мы можем поставить магниты с южным полюсом во все клетки и не использовать ни одного магнита с северным полюсом. Поскольку нет ни одной черной клетки, это будет корректной расстановкой магнитов.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="17cf6fead3b9efd88c23a75fa48c039d"/> <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="fc28f014ca80adf5f290c143b1f2317a08e23c98"/> <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='17cf6fead3b9efd88c23a75fa48c039d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1345%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='17cf6fead3b9efd88c23a75fa48c039d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1345">Codeforces Round 639 (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='17cf6fead3b9efd88c23a75fa48c039d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1345/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound 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='17cf6fead3b9efd88c23a75fa48c039d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600710"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='17cf6fead3b9efd88c23a75fa48c039d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600710"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10844" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10857" resourceName="Codeforces Round #639 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/1345">Задачи</a></li> <li><a href="/contest/1345/submit">Отослать</a></li> <li><a href="/contest/1345/my">Мои посылки</a></li> <li><a href="/contest/1345/status">Статус</a></li> <li><a href="/contest/1345/hacks">Взломы</a></li> <li><a href="/contest/1345/room/1">Комната</a></li> <li><a href="/contest/1345/standings">Положение</a></li> <li><a href="/contest/1345/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3fe7d1727f1879c94bc06df756c24cfbaf3d62d2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Однополюсные магниты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Однополюсный магнит — это магнит, у которого ровно один полюс: либо северный, либо южный. Они не существуют в природе, потому что настоящие магниты имеют два полюса, но это задача по программированию, поэтому будем считать, что такие магниты существуют.</p><p>У вас есть таблица размером $$$n\times m$$$. Изначально вы можете поставить несколько магнитов с северным полюсом и несколько магнитов с южным полюсом в некоторые клетки этой таблицы. Вам разрешено расставлять сколько угодно магнитов, в том числе несколько в одну клетку.</p><p>Можно выполнять следующую операцию: выбрать один магнит с северным полюсом и один магнит с южным полюсом для активации. Если они находятся в одной строке или в одном столбце, но занимают разные клетки, то магнит с северным полюсом переместится на одну клетку ближе к магниту с южным полюсом. Иначе, если они занимают одинаковые клетки или не находятся в одной строке или в одном столбце, то ничего не произойдет. Обратите внимание, что магниты с южным полюсом неподвижны.</p><p>Каждая клетка таблицы покрашена в черный или белый цвет. Будем рассматривать расстановки магнитов в таблице, для которых следующие условия будут выполнены.</p><ol> <li> В каждой строке и каждом столбце таблицы находится хотя бы один магнит с южным полюсом. </li><li> Если клетка таблицы черная, тогда можно переместить какой-нибудь магнит с северным полюсом в эту клетку с помощью некоторой последовательности операций <span class="tex-font-style-bf">из начального расположения магнитов</span>. </li><li> Если клетка таблицы белая, тогда никакой магнит с северным полюсом невозможно переместить в эту клетку с помощью некоторой последовательности операций <span class="tex-font-style-bf">из начального расположения магнитов</span>. </li></ol><p>Определите, можно ли расположить магниты в таблице так, что все условия будут выполнены. Если это возможно, найдите минимальное количество магнитов с северным полюсом, которое для этого требуется (минимизировать количество магнитов с южным полюсом не нужно).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$1\le n,m\le 1000$$$)  — количество строк и столбцов в таблице, соответственно.</p><p>Следующие $$$n$$$ строк описывают раскраску таблицы: $$$i$$$-я из этих строк содержит строку длины $$$m$$$, в которой $$$j$$$-й символ обозначает цвет клетки таблицы, находящейся в строке $$$i$$$ и столбце $$$j$$$. Символы «<span class="tex-font-style-tt">#</span>» и «<span class="tex-font-style-tt">.</span>» обозначают черный и белый цвета соответственно. Гарантируется, что строка не содержит других символов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число, которое равно минимальному количеству магнитов с северным полюсом, которое требуется.</p><p>Если не существует способа расставить магниты, который будет удовлетворять всем условиям, выведите единственное целое число $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 .#. ### ##. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 ## .# .# ## </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 ....# ####. .###. .#... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 . # </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 ..... ..... ..... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте возможно расположить магниты следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f89d8c7a378384a96c7e162b53499c211fbb21cd.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором тесте можно показать, что не существует необходимых расположений магнитов. На следующей картинке показаны три примера расположений, которые удовлетворяют не всем условиям. Первый пример нарушает правило $$$3$$$, потому что мы можем переместить магнит с северным полюсом вниз на белую клетку. Второй пример нарушает правило $$$2$$$, потому что мы не можем переместить магнит с северным полюсом в левую нижнюю черную клетку никакой последовательностью операций. Третий пример нарушает правило $$$1$$$, потому что нет ни одного магнита с южным полюсом в первом столбце.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4bf25d94e49a452e00895f940f4e76d26d8cde35.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Следующая картинка показывает пример возможного расположения магнитов в третьем тесте. Можно показать, что не существует необходимых расположений магнитов с меньшим количеством магнитов с северным полюсом.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/730abcba1dab5abea574d5f479fe54cdf3f528ae.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во четвертом тесте можно показать, что не существует необходимых расположений магнитов. На следующей картинке два примера расположений, которые удовлетворяют не всем условиям. Первый пример нарушает правило $$$1$$$, потому что нет ни одного магнита с южным полюсом в первой строке. Второй пример нарушает правила $$$1$$$ и $$$3$$$, потому что нет ни одного магнита с южным полюсом во второй строке, а кроме того, мы можем переместить магнит с северным полюсом на одну клетку вверх, и он попадет на белую клетку.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c719c90077972d8befc8234a02d55b35d7736299.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В пятом тесте мы можем поставить магниты с южным полюсом во все клетки и не использовать ни одного магнита с северным полюсом. Поскольку нет ни одной черной клетки, это будет корректной расстановкой магнитов.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'81249f8ebc6d7903',t:'MTY5NjY2NTc2MS4yNzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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"]
["\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\u043d\u043c", "*2000"]
1345E
1345
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-bf">Множество вещественных чисел содержит ноль и отрицательные числа.</span> Есть два вида кванторов: всеобщности ($$$\forall$$$) и существования ($$$\exists$$$). Вы можете прочитать больше про них <a href="https://ru.wikipedia.org/wiki/Квантор">здесь</a>.</p><p>Квантор всеобщности используется, чтобы сказать, что утверждение выполнено <span class="tex-font-style-it">для всех вещественных чисел</span>. Например:</p><ul> <li> $$$\forall x,x&lt;100$$$ читается как: для всех вещественных чисел $$$x$$$ число $$$x$$$ меньше, чем $$$100$$$. Это утверждение ложно. </li><li> $$$\forall x,x&gt;x-1$$$ читается как: для всех вещественных чисел $$$x$$$ число $$$x$$$ больше, чем $$$x-1$$$. Это утверждение верно. </li></ul><p>Квантор существования используется, чтобы сказать, что <span class="tex-font-style-it">существует некоторое вещественное число</span>, для которого утверждение выполнено. Например:</p><ul> <li> $$$\exists x,x&lt;100$$$ читается как: существует вещественное число $$$x$$$ такое, что $$$x$$$ меньше, чем $$$100$$$. Это утверждение верно. </li><li> $$$\exists x,x&gt;x-1$$$ читается как: существует вещественное число $$$x$$$ такое, что $$$x$$$ больше, чем $$$x-1$$$. Это утверждение верно. </li></ul><p>Кроме того, эти кванторы могут быть вложенными. Например:</p><ul> <li> $$$\forall x,\exists y,x&lt;y$$$ читается так: для всех вещественных чисел $$$x$$$ существует вещественное число $$$y$$$ такое, что $$$x$$$ меньше, чем $$$y$$$. Это утверждение верно для всех $$$x$$$, потому что существует $$$y=x+1$$$. </li><li> $$$\exists y,\forall x,x&lt;y$$$ читается так: существует вещественное число $$$y$$$ такое, что для всех вещественных чисел $$$x$$$ число $$$x$$$ меньше, чем $$$y$$$. Это утверждение ложно, потому что оно утверждает, что существует максимальное вещественное число: число $$$y$$$ больше, чем любое $$$x$$$. </li></ul><p><span class="tex-font-style-bf">Обратите внимание, что порядок переменных и кванторов важен для значения и верности утверждения.</span></p><p>Всего есть $$$n$$$ переменных $$$x_1,x_2,\ldots,x_n$$$, и вам дана формула вида $$$$$$ f(x_1,\dots,x_n):=(x_{j_1}&lt;x_{k_1})\land (x_{j_2}&lt;x_{k_2})\land \cdots\land (x_{j_m}&lt;x_{k_m}), $$$$$$</p><p>где $$$\land$$$ обозначает логическое И. Это означает, что $$$f(x_1,\ldots, x_n)$$$ истинно, если каждое неравенство $$$x_{j_i}&lt;x_{k_i}$$$ выполнено. Иначе, если хотя бы одно неравенство не выполнено, то $$$f(x_1,\ldots,x_n)$$$ ложно.</p><p>Ваша задача — выбрать значения каждого из кванторов $$$Q_1,\ldots,Q_n$$$ либо квантором всеобщности ($$$\forall$$$), либо квантором существования ($$$\exists$$$) так, что утверждение $$$$$$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$$$$$</p><p>будет верно и <span class="tex-font-style-bf">количество кванторов всеобщности максимально возможное</span>, или определить, что утверждение ложно для всех возможных выборов кванторов.</p><p><span class="tex-font-style-bf">Обратите внимание, что порядок переменных, в котором они идут в утверждении фиксирован.</span> Например, если $$$f(x_1,x_2):=(x_1&lt;x_2)$$$, то вам не разрешено сделать переменную $$$x_2$$$ идущей первой, и получить утверждение $$$\forall x_2,\exists x_1, x_1&lt;x_2$$$. Если вы выберете $$$Q_1=\exists$$$ и $$$Q_2=\forall$$$ получившееся утверждение будет <span class="tex-font-style-bf">однозначно</span> равно $$$\exists x_1,\forall x_2,x_1&lt;x_2$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$; $$$1\le m\le 2\cdot 10^5$$$) — количество переменных и неравенств в формуле, соответственно.</p><p>Следующие $$$m$$$ строк описывают формулу. $$$i$$$-я из этих строк содержит два целых числа $$$j_i$$$, $$$k_i$$$ ($$$1\le j_i,k_i\le n$$$, $$$j_i\ne k_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если ни одной расстановки кванторов такой, что утверждение будет верно, не существует, выведите единственное целое число $$$-1$$$.</p><p>Иначе на первой строке выведите максимальное возможное количество кванторов всеобщности.</p><p>На следующей строке выведите строку длины $$$n$$$, в которой $$$i$$$-й символ это «<span class="tex-font-style-tt">A</span>», если $$$Q_i$$$ должен быть квантором всеобщности ($$$\forall$$$), или «<span class="tex-font-style-tt">E</span>», если $$$Q_i$$$ должен быть квантором существования ($$$\exists$$$). Все символы должны быть в верхнем регистре. Если существует несколько возможных решений, в которых количество кванторов всеобщности максимально возможное, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 AE </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 2 3 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 1 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 AAE </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте утверждение $$$\forall x_1, \exists x_2, x_1&lt;x_2$$$ верно. Ответы «<span class="tex-font-style-tt">EA</span>» и «<span class="tex-font-style-tt">AA</span>» дают ложные утверждения. Ответ «<span class="tex-font-style-tt">EE</span>» дает верное утверждение, но количество кванторов всеобщности будет меньше, чем в нашем ответе.</p><p>Для второго теста можно показать, что ни одной расстановки кванторов такой, что утверждение будет верно, не существует.</p><p>В третьем тесте утверждение $$$\forall x_1, \forall x_2, \exists x_3, (x_1&lt;x_3)\land (x_2&lt;x_3)$$$ верно: мы можем выбрать $$$x_3=\max\{x_1,x_2\}+1$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="916daf2a7b1cf6176bcff4554fd5af2b"/> <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="fc28f014ca80adf5f290c143b1f2317a08e23c98"/> <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='916daf2a7b1cf6176bcff4554fd5af2b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1345%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='916daf2a7b1cf6176bcff4554fd5af2b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1345">Codeforces Round 639 (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='916daf2a7b1cf6176bcff4554fd5af2b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1345/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='916daf2a7b1cf6176bcff4554fd5af2b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600711"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='916daf2a7b1cf6176bcff4554fd5af2b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600711"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10844" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10857" resourceName="Codeforces Round #639 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/1345">Задачи</a></li> <li><a href="/contest/1345/submit">Отослать</a></li> <li><a href="/contest/1345/my">Мои посылки</a></li> <li><a href="/contest/1345/status">Статус</a></li> <li><a href="/contest/1345/hacks">Взломы</a></li> <li><a href="/contest/1345/room/1">Комната</a></li> <li><a href="/contest/1345/standings">Положение</a></li> <li><a href="/contest/1345/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_93e19c41e12b8c8795bfae33b8cef17888692033"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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-bf">Множество вещественных чисел содержит ноль и отрицательные числа.</span> Есть два вида кванторов: всеобщности ($$$\forall$$$) и существования ($$$\exists$$$). Вы можете прочитать больше про них <a href="https://ru.wikipedia.org/wiki/Квантор">здесь</a>.</p><p>Квантор всеобщности используется, чтобы сказать, что утверждение выполнено <span class="tex-font-style-it">для всех вещественных чисел</span>. Например:</p><ul> <li> $$$\forall x,x&lt;100$$$ читается как: для всех вещественных чисел $$$x$$$ число $$$x$$$ меньше, чем $$$100$$$. Это утверждение ложно. </li><li> $$$\forall x,x&gt;x-1$$$ читается как: для всех вещественных чисел $$$x$$$ число $$$x$$$ больше, чем $$$x-1$$$. Это утверждение верно. </li></ul><p>Квантор существования используется, чтобы сказать, что <span class="tex-font-style-it">существует некоторое вещественное число</span>, для которого утверждение выполнено. Например:</p><ul> <li> $$$\exists x,x&lt;100$$$ читается как: существует вещественное число $$$x$$$ такое, что $$$x$$$ меньше, чем $$$100$$$. Это утверждение верно. </li><li> $$$\exists x,x&gt;x-1$$$ читается как: существует вещественное число $$$x$$$ такое, что $$$x$$$ больше, чем $$$x-1$$$. Это утверждение верно. </li></ul><p>Кроме того, эти кванторы могут быть вложенными. Например:</p><ul> <li> $$$\forall x,\exists y,x&lt;y$$$ читается так: для всех вещественных чисел $$$x$$$ существует вещественное число $$$y$$$ такое, что $$$x$$$ меньше, чем $$$y$$$. Это утверждение верно для всех $$$x$$$, потому что существует $$$y=x+1$$$. </li><li> $$$\exists y,\forall x,x&lt;y$$$ читается так: существует вещественное число $$$y$$$ такое, что для всех вещественных чисел $$$x$$$ число $$$x$$$ меньше, чем $$$y$$$. Это утверждение ложно, потому что оно утверждает, что существует максимальное вещественное число: число $$$y$$$ больше, чем любое $$$x$$$. </li></ul><p><span class="tex-font-style-bf">Обратите внимание, что порядок переменных и кванторов важен для значения и верности утверждения.</span></p><p>Всего есть $$$n$$$ переменных $$$x_1,x_2,\ldots,x_n$$$, и вам дана формула вида $$$$$$ f(x_1,\dots,x_n):=(x_{j_1}&lt;x_{k_1})\land (x_{j_2}&lt;x_{k_2})\land \cdots\land (x_{j_m}&lt;x_{k_m}), $$$$$$</p><p>где $$$\land$$$ обозначает логическое И. Это означает, что $$$f(x_1,\ldots, x_n)$$$ истинно, если каждое неравенство $$$x_{j_i}&lt;x_{k_i}$$$ выполнено. Иначе, если хотя бы одно неравенство не выполнено, то $$$f(x_1,\ldots,x_n)$$$ ложно.</p><p>Ваша задача — выбрать значения каждого из кванторов $$$Q_1,\ldots,Q_n$$$ либо квантором всеобщности ($$$\forall$$$), либо квантором существования ($$$\exists$$$) так, что утверждение $$$$$$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$$$$$</p><p>будет верно и <span class="tex-font-style-bf">количество кванторов всеобщности максимально возможное</span>, или определить, что утверждение ложно для всех возможных выборов кванторов.</p><p><span class="tex-font-style-bf">Обратите внимание, что порядок переменных, в котором они идут в утверждении фиксирован.</span> Например, если $$$f(x_1,x_2):=(x_1&lt;x_2)$$$, то вам не разрешено сделать переменную $$$x_2$$$ идущей первой, и получить утверждение $$$\forall x_2,\exists x_1, x_1&lt;x_2$$$. Если вы выберете $$$Q_1=\exists$$$ и $$$Q_2=\forall$$$ получившееся утверждение будет <span class="tex-font-style-bf">однозначно</span> равно $$$\exists x_1,\forall x_2,x_1&lt;x_2$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$; $$$1\le m\le 2\cdot 10^5$$$) — количество переменных и неравенств в формуле, соответственно.</p><p>Следующие $$$m$$$ строк описывают формулу. $$$i$$$-я из этих строк содержит два целых числа $$$j_i$$$, $$$k_i$$$ ($$$1\le j_i,k_i\le n$$$, $$$j_i\ne k_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если ни одной расстановки кванторов такой, что утверждение будет верно, не существует, выведите единственное целое число $$$-1$$$.</p><p>Иначе на первой строке выведите максимальное возможное количество кванторов всеобщности.</p><p>На следующей строке выведите строку длины $$$n$$$, в которой $$$i$$$-й символ это «<span class="tex-font-style-tt">A</span>», если $$$Q_i$$$ должен быть квантором всеобщности ($$$\forall$$$), или «<span class="tex-font-style-tt">E</span>», если $$$Q_i$$$ должен быть квантором существования ($$$\exists$$$). Все символы должны быть в верхнем регистре. Если существует несколько возможных решений, в которых количество кванторов всеобщности максимально возможное, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 AE </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 2 3 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 1 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 AAE </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте утверждение $$$\forall x_1, \exists x_2, x_1&lt;x_2$$$ верно. Ответы «<span class="tex-font-style-tt">EA</span>» и «<span class="tex-font-style-tt">AA</span>» дают ложные утверждения. Ответ «<span class="tex-font-style-tt">EE</span>» дает верное утверждение, но количество кванторов всеобщности будет меньше, чем в нашем ответе.</p><p>Для второго теста можно показать, что ни одной расстановки кванторов такой, что утверждение будет верно, не существует.</p><p>В третьем тесте утверждение $$$\forall x_1, \forall x_2, \exists x_3, (x_1&lt;x_3)\land (x_2&lt;x_3)$$$ верно: мы можем выбрать $$$x_3=\max\{x_1,x_2\}+1$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:02: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:'81249f979def1640',t:'MTY5NjY2NTc2Mi41NTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2600"]
1345F
1345
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><span class="tex-font-style-it">О нет! Скоро закончится время, когда еще можно подать заявку на стажировку в IT компанию, а вы медлили, участвуя в контестах вместо этого! (Давайте пока притворимся, что в наше неопределенное время можно будет найти работу.)</span></p><p>Вы сделали много проектов по программированию. Существует ровно $$$n$$$ типов проектов и вы сделали $$$a_i$$$ проектов типа $$$i$$$. Ваше резюме имеет ограниченный размер, но вы хотите аккуратно выбрать проекты, чтобы максимизировать шанс того, что вас возьмут на работу.</p><p>Вы хотите включить несколько проектов одного типа, чтобы подчеркнуть вашу компетентность, но вы также не хотите включать их так много, что среди них начнут появляться некачественные проекты. Поэтому, вы придумали следующую формулу, которая является хорошим индикатором того, что вас возьмут на работу:</p><p>$$$$$$ f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). $$$$$$</p><p>Здесь $$$b_i$$$ обозначает количество проектов типа $$$i$$$, которое вы включите в ваше резюме. Конечно, вы не можете включить в резюме больше проектов, чем вы сделали, поэтому для всех $$$i$$$ должно быть выполнено $$$0\le b_i \le a_i$$$.</p><p>В вашем резюме хватает места для $$$k$$$ проектов, и вы абсолютно точно не будете приняты на работу, если в вашем резюме будет пустая строчка. Поэтому вы хотите, чтобы было выполнено $$$\sum\limits_{i=1}^n b_i=k$$$.</p><p>Найдите значения $$$b_1,\ldots, b_n$$$, которые максимизируют значение $$$f(b_1,\ldots,b_n)$$$ при том, что все описанные условия выполнены.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$k$$$ ($$$1\le n\le 10^5$$$, $$$1\le k\le \sum\limits_{i=1}^n a_i$$$) — количество типов проектов и размер резюме, соответственно.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$), $$$a_i$$$ равно количеству сделанных проектов типа $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$n$$$ целых чисел $$$b_1,\ldots, b_n$$$, для которых достигается максимальное значение $$$f(b_1,\ldots,b_n)$$$ в условиях ограничений $$$0\le b_i\le a_i$$$ и $$$\sum\limits_{i=1}^n b_i=k$$$. Если существует несколько возможных решений, выведите любое.</p><p><span class="tex-font-style-bf">Обратите внимание, что вы не должны выводить само значение $$$f(b_1,\ldots,b_n)$$$.</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 32 1 2 3 4 5 5 5 5 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 3 4 4 4 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 8 4 4 8 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 2 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте оптимальный ответ это $$$f=-269$$$. Обратите внимание, что большее значение $$$f$$$ возможно, только если мы уберем ограничение $$$\sum\limits_{i=1}^n b_i=k$$$.</p><p>Во втором тесте оптимальный ответ $$$f=9$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="adbfde8436bb4d6632d241a477333a11"/> <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="fc28f014ca80adf5f290c143b1f2317a08e23c98"/> <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='adbfde8436bb4d6632d241a477333a11'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1345%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='adbfde8436bb4d6632d241a477333a11'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1345">Codeforces Round 639 (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='adbfde8436bb4d6632d241a477333a11'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1345/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='adbfde8436bb4d6632d241a477333a11'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="600712"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='adbfde8436bb4d6632d241a477333a11'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="600712"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76777" title="Codeforces Round #639" target="_blank">Codeforces Round #639 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10844" resourceName="Codeforces Round #639" resourceManual="true" src="//codeforces.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/76819" title="Codeforces Round #639 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10857" resourceName="Codeforces Round #639 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/1345">Задачи</a></li> <li><a href="/contest/1345/submit">Отослать</a></li> <li><a href="/contest/1345/my">Мои посылки</a></li> <li><a href="/contest/1345/status">Статус</a></li> <li><a href="/contest/1345/hacks">Взломы</a></li> <li><a href="/contest/1345/room/1">Комната</a></li> <li><a href="/contest/1345/standings">Положение</a></li> <li><a href="/contest/1345/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_65727f676c2b63f35637ebaaa505845e6b67e208"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><span class="tex-font-style-it">О нет! Скоро закончится время, когда еще можно подать заявку на стажировку в IT компанию, а вы медлили, участвуя в контестах вместо этого! (Давайте пока притворимся, что в наше неопределенное время можно будет найти работу.)</span></p><p>Вы сделали много проектов по программированию. Существует ровно $$$n$$$ типов проектов и вы сделали $$$a_i$$$ проектов типа $$$i$$$. Ваше резюме имеет ограниченный размер, но вы хотите аккуратно выбрать проекты, чтобы максимизировать шанс того, что вас возьмут на работу.</p><p>Вы хотите включить несколько проектов одного типа, чтобы подчеркнуть вашу компетентность, но вы также не хотите включать их так много, что среди них начнут появляться некачественные проекты. Поэтому, вы придумали следующую формулу, которая является хорошим индикатором того, что вас возьмут на работу:</p><p>$$$$$$ f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). $$$$$$</p><p>Здесь $$$b_i$$$ обозначает количество проектов типа $$$i$$$, которое вы включите в ваше резюме. Конечно, вы не можете включить в резюме больше проектов, чем вы сделали, поэтому для всех $$$i$$$ должно быть выполнено $$$0\le b_i \le a_i$$$.</p><p>В вашем резюме хватает места для $$$k$$$ проектов, и вы абсолютно точно не будете приняты на работу, если в вашем резюме будет пустая строчка. Поэтому вы хотите, чтобы было выполнено $$$\sum\limits_{i=1}^n b_i=k$$$.</p><p>Найдите значения $$$b_1,\ldots, b_n$$$, которые максимизируют значение $$$f(b_1,\ldots,b_n)$$$ при том, что все описанные условия выполнены.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$k$$$ ($$$1\le n\le 10^5$$$, $$$1\le k\le \sum\limits_{i=1}^n a_i$$$) — количество типов проектов и размер резюме, соответственно.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$), $$$a_i$$$ равно количеству сделанных проектов типа $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$n$$$ целых чисел $$$b_1,\ldots, b_n$$$, для которых достигается максимальное значение $$$f(b_1,\ldots,b_n)$$$ в условиях ограничений $$$0\le b_i\le a_i$$$ и $$$\sum\limits_{i=1}^n b_i=k$$$. Если существует несколько возможных решений, выведите любое.</p><p><span class="tex-font-style-bf">Обратите внимание, что вы не должны выводить само значение $$$f(b_1,\ldots,b_n)$$$.</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 32 1 2 3 4 5 5 5 5 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 3 4 4 4 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 8 4 4 8 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 2 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте оптимальный ответ это $$$f=-269$$$. Обратите внимание, что большее значение $$$f$$$ возможно, только если мы уберем ограничение $$$\sum\limits_{i=1}^n b_i=k$$$.</p><p>Во втором тесте оптимальный ответ $$$f=9$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'81249f9fae2b7a71',t:'MTY5NjY2NTc2My44NDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*2700"]
1348A
1348
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$$$ монет с весами $$$2^1, 2^2, \dots, 2^n$$$. Он знает, что $$$n$$$ — четное.</p><p>Он хочет сложить монеты в две кучки так, что в каждой кучке будет ровно $$$\frac{n}{2}$$$ монет и разница суммарных весов между кучками будет <span class="tex-font-style-bf">минимальна</span>. Формально, обозначим за $$$a$$$ сумму весов в первой кучке, а за $$$b$$$ — сумму весов во второй. Помогите Фениксу минимизировать $$$|a-b|$$$, то есть модуль числа $$$a-b$$$.</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 30$$$; $$$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> 2 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, у Феникса есть две монеты с весами $$$2$$$ и $$$4$$$. Как бы он ни разделил монеты, разница будет равна $$$4-2=2$$$.</p><p>Во втором наборе входных данных, у Феникса есть четыре монеты с весами $$$2$$$, $$$4$$$, $$$8$$$ и $$$16$$$. Фениксу выгодно положить монеты с весами $$$2$$$ и $$$16$$$ в одну кучку, а монеты с весами $$$4$$$ и $$$8$$$ — в другую. Разница будет равна $$$(2+16)-(4+8)=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="3d90d80f07b81763426d497b103d4ab0"/> <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="82ad588e24c9494a01d2e5060ebb4201beecaa76"/> <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='3d90d80f07b81763426d497b103d4ab0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1348%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='3d90d80f07b81763426d497b103d4ab0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1348">Codeforces Round 638 (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='3d90d80f07b81763426d497b103d4ab0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1348/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='3d90d80f07b81763426d497b103d4ab0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="609088"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3d90d80f07b81763426d497b103d4ab0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="609088"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76696" title="Codeforces Round #638 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10831" resourceName="Codeforces Round #638 (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/76555" title="Codeforces Round #638 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10842" resourceName="Codeforces Round #638 (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/1348">Задачи</a></li> <li><a href="/contest/1348/submit">Отослать</a></li> <li><a href="/contest/1348/my">Мои посылки</a></li> <li><a href="/contest/1348/status">Статус</a></li> <li><a href="/contest/1348/hacks">Взломы</a></li> <li><a href="/contest/1348/room/1">Комната</a></li> <li><a href="/contest/1348/standings">Положение</a></li> <li><a href="/contest/1348/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_be3ed78cc06f7ffbb1b8fb68113f40f760a71acc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ монет с весами $$$2^1, 2^2, \dots, 2^n$$$. Он знает, что $$$n$$$ — четное.</p><p>Он хочет сложить монеты в две кучки так, что в каждой кучке будет ровно $$$\frac{n}{2}$$$ монет и разница суммарных весов между кучками будет <span class="tex-font-style-bf">минимальна</span>. Формально, обозначим за $$$a$$$ сумму весов в первой кучке, а за $$$b$$$ — сумму весов во второй. Помогите Фениксу минимизировать $$$|a-b|$$$, то есть модуль числа $$$a-b$$$.</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 30$$$; $$$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> 2 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, у Феникса есть две монеты с весами $$$2$$$ и $$$4$$$. Как бы он ни разделил монеты, разница будет равна $$$4-2=2$$$.</p><p>Во втором наборе входных данных, у Феникса есть четыре монеты с весами $$$2$$$, $$$4$$$, $$$8$$$ и $$$16$$$. Фениксу выгодно положить монеты с весами $$$2$$$ и $$$16$$$ в одну кучку, а монеты с весами $$$4$$$ и $$$8$$$ — в другую. Разница будет равна $$$(2+16)-(4+8)=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 11:02:45</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:'81249fa7be5e16b7',t:'MTY5NjY2NTc2NS4yNTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"]
1348B
1348
B
ru
B. Феникс и красота
<div class="problem-statement"><div class="header"><div class="title">B. Феникс и красота</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Феникс любит красивые массивы. Он считает массив красивым, если все его подмассивы длины $$$k$$$ имеют равную сумму. Подмассив массива — это последовательность подряд идущих элементов массива.</p><p>У Феникса есть массив $$$a$$$ длины $$$n$$$. Он хочет вставить несколько (возможно, ноль) целых чисел в свой массив, чтобы он стал красивым. Вставляемые числа должны иметь значения от $$$1$$$ по $$$n$$$ включительно. Числа можно вставлять куда угодно (даже перед первым или после последнего элемента). Феникс <span class="tex-font-style-bf">не пытается</span> минимизировать количество вставленных чисел.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов. В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 50$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных задано два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 100$$$).</p><p>Во второй строке каждого набора задано $$$n$$$ целых чисел через пробел ($$$1 \le a_i \le n$$$) — первоначальный массив Феникса. Массив уже может быть красивым, а может и не быть.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если невозможно получить крассивый массив, выведите <span class="tex-font-style-tt">-1</span>. Иначе, выведите две строки.</p><p>В первой строке выведите длину красивого массива $$$m$$$ ($$$n \le m \le 10^4$$$). Вам не нужно минимизировать $$$m$$$.</p><p>Во второй строке выведите $$$m$$$ целых чисел через пробел ($$$1 \le b_i \le n$$$) — красивый массив, который Феникс сможет получить вставляя несколько (возможно, ноль) целых чисел в свой массив $$$a$$$. Вы можете выводить числа, которых не было в массиве $$$a$$$ первоначально.</p><p>Если существует несколько решений, выведите любое. Гарантируется, что если мы можем сделать массив $$$a$$$ красивым, то мы всегда сможем добиться этого при итоговой длине не более $$$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> 4 4 2 1 2 2 1 4 3 1 2 2 1 3 2 1 2 3 4 4 4 3 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 2 1 2 1 4 1 2 2 1 -1 7 4 3 2 1 4 3 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, мы можем сделать массив $$$a$$$ красивым, если вставим число $$$1$$$ в позицию $$$3$$$ (между двумя числами $$$2$$$). Теперь все подмассивы длины $$$k=2$$$ будут иметь одинаковую сумму $$$3$$$. Существует много других возможных решений, например: </p><ul> <li> $$$2, 1, 2, 1, 2, 1$$$ </li><li> $$$1, 2, 1, 2, 1, 2$$$ </li></ul><p>Во втором наборе, массив уже красивый: все подмассивы длины $$$k=3$$$ имеют одинаковую сумму $$$5$$$.</p><p>В третьем наборе, можно показать, что невозможно вставить числа так, чтобы сделать массив $$$a$$$ красивым.</p><p>В четвертом наборе, предложенный массив $$$b$$$ является красивым — все его подмассивы длины $$$k=4$$$ имеют равную сумму $$$10$$$. Также существуют и другие решения.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="877550316658c7a431435c6555aacd6b"/> <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="82ad588e24c9494a01d2e5060ebb4201beecaa76"/> <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='877550316658c7a431435c6555aacd6b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1348%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='877550316658c7a431435c6555aacd6b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1348">Codeforces Round 638 (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='877550316658c7a431435c6555aacd6b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1348/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='877550316658c7a431435c6555aacd6b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="609089"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='877550316658c7a431435c6555aacd6b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="609089"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76696" title="Codeforces Round #638 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10831" resourceName="Codeforces Round #638 (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/76555" title="Codeforces Round #638 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10842" resourceName="Codeforces Round #638 (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/1348">Задачи</a></li> <li><a href="/contest/1348/submit">Отослать</a></li> <li><a href="/contest/1348/my">Мои посылки</a></li> <li><a href="/contest/1348/status">Статус</a></li> <li><a href="/contest/1348/hacks">Взломы</a></li> <li><a href="/contest/1348/room/1">Комната</a></li> <li><a href="/contest/1348/standings">Положение</a></li> <li><a href="/contest/1348/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d077ec7c265c5a38e9ac149ae321c477b4815ead"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Феникс и красота</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Феникс любит красивые массивы. Он считает массив красивым, если все его подмассивы длины $$$k$$$ имеют равную сумму. Подмассив массива — это последовательность подряд идущих элементов массива.</p><p>У Феникса есть массив $$$a$$$ длины $$$n$$$. Он хочет вставить несколько (возможно, ноль) целых чисел в свой массив, чтобы он стал красивым. Вставляемые числа должны иметь значения от $$$1$$$ по $$$n$$$ включительно. Числа можно вставлять куда угодно (даже перед первым или после последнего элемента). Феникс <span class="tex-font-style-bf">не пытается</span> минимизировать количество вставленных чисел.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов. В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 50$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных задано два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 100$$$).</p><p>Во второй строке каждого набора задано $$$n$$$ целых чисел через пробел ($$$1 \le a_i \le n$$$) — первоначальный массив Феникса. Массив уже может быть красивым, а может и не быть.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если невозможно получить крассивый массив, выведите <span class="tex-font-style-tt">-1</span>. Иначе, выведите две строки.</p><p>В первой строке выведите длину красивого массива $$$m$$$ ($$$n \le m \le 10^4$$$). Вам не нужно минимизировать $$$m$$$.</p><p>Во второй строке выведите $$$m$$$ целых чисел через пробел ($$$1 \le b_i \le n$$$) — красивый массив, который Феникс сможет получить вставляя несколько (возможно, ноль) целых чисел в свой массив $$$a$$$. Вы можете выводить числа, которых не было в массиве $$$a$$$ первоначально.</p><p>Если существует несколько решений, выведите любое. Гарантируется, что если мы можем сделать массив $$$a$$$ красивым, то мы всегда сможем добиться этого при итоговой длине не более $$$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> 4 4 2 1 2 2 1 4 3 1 2 2 1 3 2 1 2 3 4 4 4 3 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 2 1 2 1 4 1 2 2 1 -1 7 4 3 2 1 4 3 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, мы можем сделать массив $$$a$$$ красивым, если вставим число $$$1$$$ в позицию $$$3$$$ (между двумя числами $$$2$$$). Теперь все подмассивы длины $$$k=2$$$ будут иметь одинаковую сумму $$$3$$$. Существует много других возможных решений, например: </p><ul> <li> $$$2, 1, 2, 1, 2, 1$$$ </li><li> $$$1, 2, 1, 2, 1, 2$$$ </li></ul><p>Во втором наборе, массив уже красивый: все подмассивы длины $$$k=3$$$ имеют одинаковую сумму $$$5$$$.</p><p>В третьем наборе, можно показать, что невозможно вставить числа так, чтобы сделать массив $$$a$$$ красивым.</p><p>В четвертом наборе, предложенный массив $$$b$$$ является красивым — все его подмассивы длины $$$k=4$$$ имеют равную сумму $$$10$$$. Также существуют и другие решения.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:02: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:'81249fb07b60149c',t:'MTY5NjY2NTc2Ni43OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1400"]
1348C
1348
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$$$, состоящая из строчных букв латинского алфавита. Он хочет распределить все буквы своей строки по $$$k$$$ <span class="tex-font-style-bf">непустым</span> строкам $$$a_1, a_2, \dots, a_k$$$ так, что каждая буква из $$$s$$$ попадет ровно в одну из строк $$$a_i$$$. Строки $$$a_i$$$ <span class="tex-font-style-bf">не обязаны</span> быть подстроками $$$s$$$. Феникс может распределить буквы $$$s$$$ и переупорядочить их внутри каждой строки $$$a_i$$$ так как захочет.</p><p>Например, если $$$s = $$$ <span class="tex-font-style-tt">baba</span> и $$$k=2$$$, Феникс может распределить буквы своей строки множеством способов, в том числе: </p><ul> <li> <span class="tex-font-style-tt">ba</span> и <span class="tex-font-style-tt">ba</span> </li><li> <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">abb</span> </li><li> <span class="tex-font-style-tt">ab</span> и <span class="tex-font-style-tt">ab</span> </li><li> <span class="tex-font-style-tt">bb</span> и <span class="tex-font-style-tt">aa</span> </li></ul><p>Однако получить такие варианты он не может: </p><ul> <li> <span class="tex-font-style-tt">baa</span> и <span class="tex-font-style-tt">ba</span> </li><li> <span class="tex-font-style-tt">b</span> и <span class="tex-font-style-tt">ba</span> </li><li> <span class="tex-font-style-tt">baba</span> и пустая строка ($$$a_i$$$ должны быть непустыми) </li></ul><p>Феникс хочет разделить свою строку $$$s$$$ на $$$k$$$ строк $$$a_1, a_2, \dots, a_k$$$ так, чтобы <span class="tex-font-style-bf">минимизировать</span> лексикографически максимальную строку среди них, т. е. минимизировать $$$max(a_1, a_2, \dots, a_k)$$$. Помогите ему найти оптимальное распределение и выведите минимально возможное значение $$$max(a_1, a_2, \dots, a_k)$$$.</p><p>Строка $$$x$$$ лексикографически меньше, чем строка $$$y$$$, если либо $$$x$$$ является префиксом $$$y$$$ (и $$$x \ne y$$$), либо существует такой индекс $$$i$$$ ($$$1 \le i \le min(|x|, |y|))$$$, что $$$x_i$$$ &lt; $$$y_i$$$ и для всех $$$j$$$ $$$(1 \le j &lt; i)$$$ $$$x_j = y_j$$$. Здесь $$$|x|$$$ обозначает длину строки $$$x$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов. В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. Каждый набор состоит из двух строк.</p><p>В первой строке каждого набора задано два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 10^5$$$)  — длина строки $$$s$$$ и количество не пустых строк, в которые Феникс хочет распределить буквы $$$s$$$, соответственно.</p><p>Во второй строке каждого набора задана строка $$$s$$$ длины $$$n$$$, состоящая из строчных латинских букв.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных $$$\le 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов — по одному на набор входных данных; $$$i$$$-й ответ — минимально возможный $$$max(a_1, a_2, \dots, a_k)$$$ в $$$i$$$-м наборе.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 4 2 baba 5 2 baacb 5 3 baacb 5 3 aaaaa 6 4 aaxxzz 7 1 phoenix </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ab abbc b aa x ehinopx </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, одно из оптимальных решений — разбить <span class="tex-font-style-tt">baba</span> на <span class="tex-font-style-tt">ab</span> и <span class="tex-font-style-tt">ab</span>. </p><p>Во втором наборе входных данных, одно из оптимальных решений — разбить <span class="tex-font-style-tt">baacb</span> на <span class="tex-font-style-tt">abbc</span> и <span class="tex-font-style-tt">a</span>.</p><p>В третьем наборе, одно из оптимальных решений — разбить <span class="tex-font-style-tt">baacb</span> на <span class="tex-font-style-tt">ac</span>, <span class="tex-font-style-tt">ab</span> и <span class="tex-font-style-tt">b</span>.</p><p>В четвертом наборе, одно из оптимальных решений — разбить <span class="tex-font-style-tt">aaaaa</span> на <span class="tex-font-style-tt">aa</span>, <span class="tex-font-style-tt">aa</span> и <span class="tex-font-style-tt">a</span>.</p><p>В пятом наборе, одно из оптимальных решений — разбить <span class="tex-font-style-tt">aaxxzz</span> на <span class="tex-font-style-tt">az</span>, <span class="tex-font-style-tt">az</span>, <span class="tex-font-style-tt">x</span> и <span class="tex-font-style-tt">x</span>.</p><p>В шестом наборе, одно из оптимальных решений — разбить <span class="tex-font-style-tt">phoenix</span> на <span class="tex-font-style-tt">ehinopx</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="e004814ea26ac4935e18a11e9d37b6d4"/> <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="82ad588e24c9494a01d2e5060ebb4201beecaa76"/> <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='e004814ea26ac4935e18a11e9d37b6d4'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1348%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='e004814ea26ac4935e18a11e9d37b6d4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1348">Codeforces Round 638 (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='e004814ea26ac4935e18a11e9d37b6d4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1348/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='e004814ea26ac4935e18a11e9d37b6d4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="609090"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e004814ea26ac4935e18a11e9d37b6d4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="609090"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76696" title="Codeforces Round #638 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10831" resourceName="Codeforces Round #638 (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/76555" title="Codeforces Round #638 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10842" resourceName="Codeforces Round #638 (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/1348">Задачи</a></li> <li><a href="/contest/1348/submit">Отослать</a></li> <li><a href="/contest/1348/my">Мои посылки</a></li> <li><a href="/contest/1348/status">Статус</a></li> <li><a href="/contest/1348/hacks">Взломы</a></li> <li><a href="/contest/1348/room/1">Комната</a></li> <li><a href="/contest/1348/standings">Положение</a></li> <li><a href="/contest/1348/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_dcd04db7ddd36c6e6c37263bb4e949a1d2a273c3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$, состоящая из строчных букв латинского алфавита. Он хочет распределить все буквы своей строки по $$$k$$$ <span class="tex-font-style-bf">непустым</span> строкам $$$a_1, a_2, \dots, a_k$$$ так, что каждая буква из $$$s$$$ попадет ровно в одну из строк $$$a_i$$$. Строки $$$a_i$$$ <span class="tex-font-style-bf">не обязаны</span> быть подстроками $$$s$$$. Феникс может распределить буквы $$$s$$$ и переупорядочить их внутри каждой строки $$$a_i$$$ так как захочет.</p><p>Например, если $$$s = $$$ <span class="tex-font-style-tt">baba</span> и $$$k=2$$$, Феникс может распределить буквы своей строки множеством способов, в том числе: </p><ul> <li> <span class="tex-font-style-tt">ba</span> и <span class="tex-font-style-tt">ba</span> </li><li> <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">abb</span> </li><li> <span class="tex-font-style-tt">ab</span> и <span class="tex-font-style-tt">ab</span> </li><li> <span class="tex-font-style-tt">bb</span> и <span class="tex-font-style-tt">aa</span> </li></ul><p>Однако получить такие варианты он не может: </p><ul> <li> <span class="tex-font-style-tt">baa</span> и <span class="tex-font-style-tt">ba</span> </li><li> <span class="tex-font-style-tt">b</span> и <span class="tex-font-style-tt">ba</span> </li><li> <span class="tex-font-style-tt">baba</span> и пустая строка ($$$a_i$$$ должны быть непустыми) </li></ul><p>Феникс хочет разделить свою строку $$$s$$$ на $$$k$$$ строк $$$a_1, a_2, \dots, a_k$$$ так, чтобы <span class="tex-font-style-bf">минимизировать</span> лексикографически максимальную строку среди них, т. е. минимизировать $$$max(a_1, a_2, \dots, a_k)$$$. Помогите ему найти оптимальное распределение и выведите минимально возможное значение $$$max(a_1, a_2, \dots, a_k)$$$.</p><p>Строка $$$x$$$ лексикографически меньше, чем строка $$$y$$$, если либо $$$x$$$ является префиксом $$$y$$$ (и $$$x \ne y$$$), либо существует такой индекс $$$i$$$ ($$$1 \le i \le min(|x|, |y|))$$$, что $$$x_i$$$ &lt; $$$y_i$$$ и для всех $$$j$$$ $$$(1 \le j &lt; i)$$$ $$$x_j = y_j$$$. Здесь $$$|x|$$$ обозначает длину строки $$$x$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов. В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. Каждый набор состоит из двух строк.</p><p>В первой строке каждого набора задано два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 10^5$$$)  — длина строки $$$s$$$ и количество не пустых строк, в которые Феникс хочет распределить буквы $$$s$$$, соответственно.</p><p>Во второй строке каждого набора задана строка $$$s$$$ длины $$$n$$$, состоящая из строчных латинских букв.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных $$$\le 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов — по одному на набор входных данных; $$$i$$$-й ответ — минимально возможный $$$max(a_1, a_2, \dots, a_k)$$$ в $$$i$$$-м наборе.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 4 2 baba 5 2 baacb 5 3 baacb 5 3 aaaaa 6 4 aaxxzz 7 1 phoenix </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ab abbc b aa x ehinopx </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, одно из оптимальных решений — разбить <span class="tex-font-style-tt">baba</span> на <span class="tex-font-style-tt">ab</span> и <span class="tex-font-style-tt">ab</span>. </p><p>Во втором наборе входных данных, одно из оптимальных решений — разбить <span class="tex-font-style-tt">baacb</span> на <span class="tex-font-style-tt">abbc</span> и <span class="tex-font-style-tt">a</span>.</p><p>В третьем наборе, одно из оптимальных решений — разбить <span class="tex-font-style-tt">baacb</span> на <span class="tex-font-style-tt">ac</span>, <span class="tex-font-style-tt">ab</span> и <span class="tex-font-style-tt">b</span>.</p><p>В четвертом наборе, одно из оптимальных решений — разбить <span class="tex-font-style-tt">aaaaa</span> на <span class="tex-font-style-tt">aa</span>, <span class="tex-font-style-tt">aa</span> и <span class="tex-font-style-tt">a</span>.</p><p>В пятом наборе, одно из оптимальных решений — разбить <span class="tex-font-style-tt">aaxxzz</span> на <span class="tex-font-style-tt">az</span>, <span class="tex-font-style-tt">az</span>, <span class="tex-font-style-tt">x</span> и <span class="tex-font-style-tt">x</span>.</p><p>В шестом наборе, одно из оптимальных решений — разбить <span class="tex-font-style-tt">phoenix</span> на <span class="tex-font-style-tt">ehinopx</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 11:02:49</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:'81249fbacbb9149c',t:'MTY5NjY2NTc2OS43NTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1600"]
1348D
1348
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>Изначально, в день $$$1$$$, есть одна бактерия массой $$$1$$$.</p><p>Каждый день некоторое количество бактерий делятся (возможно, все или ни одной). Когда бактерия массой $$$m$$$ делится, она превращается в две бактерии массой $$$\frac{m}{2}$$$ каждая. Например, бактерия массой $$$3$$$ может разделиться на две бактерии массой $$$1.5$$$.</p><p>Каждую ночь масса каждой бактерии увеличивается на один.</p><p>Феникса интересует вопрос: может ли общая масса бактерий стать в точности равна $$$n$$$. Если может, то его интересует как добиться такой массы за минимальное количество ночей. Помогите ему стать самым лучшим ученым!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов. В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора задано целое число $$$n$$$ ($$$2 \le n \le 10^9$$$) — суммарная масса бактерий, которой хочет добиться Феникс.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если не существует способа получить общую массу равную $$$n$$$, выведите <span class="tex-font-style-tt">-1</span>. В противном случае, выведите две строки.</p><p>В первой строке выведите целое число $$$d$$$ — минимальное необходимое количество ночей.</p><p>В следующей строке выведите $$$d$$$ целых чисел, где $$$i$$$-е число обозначает количество бактерий, которые поделятся в $$$i$$$-й день.</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 9 11 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 0 2 3 1 1 2 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе, можно получить общую массу бактерий ровно $$$9$$$ следующим образом: </p><ul> <li> День $$$1$$$: Бактерия с массой $$$1$$$ делится. Получаем две бактерии с массой $$$0.5$$$. </li><li> Ночь $$$1$$$: Все бактерии увеличивают массу на один. Получаем две бактерии с массой $$$1.5$$$. </li><li> День $$$2$$$: Ни одна бактерия не делится. </li><li> Ночь $$$2$$$: Получаем две бактерии с массой $$$2.5$$$. </li><li> День $$$3$$$: Обе бактерии делятся. Получаем четыре бактерии с массой $$$1.25$$$. </li><li> Ночь $$$3$$$: Получаем четыре бактерии с массой $$$2.25$$$. </li></ul> Суммарная масса равна $$$2.25+2.25+2.25+2.25=9$$$. Можно доказать, что $$$3$$$ — минимальное необходимое количество ночей. Есть и другие способы добиться суммарной массы 9 за 3 ночи.<p>$$$ $$$</p><p>В втором наборе, можно получить общую массу бактерий ровно $$$11$$$ следующим образом: </p><ul> <li> День $$$1$$$: Бактерия с массой $$$1$$$ делится. Получаем две бактерии с массой $$$0.5$$$. </li><li> Ночь $$$1$$$: Получаем две бактерии с массой $$$1.5$$$. </li><li> День $$$2$$$: Одна бактерия делится. Получаем три бактерии с массами $$$0.75$$$, $$$0.75$$$ и $$$1.5$$$. </li><li> Ночь $$$2$$$: Получаем три бактерии с массами $$$1.75$$$, $$$1.75$$$ и $$$2.5$$$. </li><li> День $$$3$$$: Бактерия с массой $$$1.75$$$ и бактерия с массой $$$2.5$$$ делятся. Получаем пять бактерий с массами $$$0.875$$$, $$$0.875$$$, $$$1.25$$$, $$$1.25$$$ и $$$1.75$$$. </li><li> Ночь $$$3$$$: Получаем пять бактерий с массами $$$1.875$$$, $$$1.875$$$, $$$2.25$$$, $$$2.25$$$ и $$$2.75$$$. </li></ul> Суммарная масса равна $$$1.875+1.875+2.25+2.25+2.75=11$$$. Можно доказать, что $$$3$$$ — минимальное необходимое количество ночей. Есть и другие способы добиться суммарной массы 11 за 3 ночи.<p>$$$ $$$</p><p>Во третьем наборе, бактерия не делится в день $$$1$$$, а потом увеличивает массу до $$$2$$$ в ночь $$$1$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a20d8e1fa196009acae42580d50c97e0"/> <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="82ad588e24c9494a01d2e5060ebb4201beecaa76"/> <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='a20d8e1fa196009acae42580d50c97e0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1348%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='a20d8e1fa196009acae42580d50c97e0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1348">Codeforces Round 638 (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='a20d8e1fa196009acae42580d50c97e0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1348/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='a20d8e1fa196009acae42580d50c97e0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="609091"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a20d8e1fa196009acae42580d50c97e0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="609091"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76696" title="Codeforces Round #638 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10831" resourceName="Codeforces Round #638 (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/76555" title="Codeforces Round #638 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10842" resourceName="Codeforces Round #638 (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/1348">Задачи</a></li> <li><a href="/contest/1348/submit">Отослать</a></li> <li><a href="/contest/1348/my">Мои посылки</a></li> <li><a href="/contest/1348/status">Статус</a></li> <li><a href="/contest/1348/hacks">Взломы</a></li> <li><a href="/contest/1348/room/1">Комната</a></li> <li><a href="/contest/1348/standings">Положение</a></li> <li><a href="/contest/1348/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_86fa421a1a4b4e45edd2ec82ceecf31b5c57e44f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Изначально, в день $$$1$$$, есть одна бактерия массой $$$1$$$.</p><p>Каждый день некоторое количество бактерий делятся (возможно, все или ни одной). Когда бактерия массой $$$m$$$ делится, она превращается в две бактерии массой $$$\frac{m}{2}$$$ каждая. Например, бактерия массой $$$3$$$ может разделиться на две бактерии массой $$$1.5$$$.</p><p>Каждую ночь масса каждой бактерии увеличивается на один.</p><p>Феникса интересует вопрос: может ли общая масса бактерий стать в точности равна $$$n$$$. Если может, то его интересует как добиться такой массы за минимальное количество ночей. Помогите ему стать самым лучшим ученым!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов. В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора задано целое число $$$n$$$ ($$$2 \le n \le 10^9$$$) — суммарная масса бактерий, которой хочет добиться Феникс.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если не существует способа получить общую массу равную $$$n$$$, выведите <span class="tex-font-style-tt">-1</span>. В противном случае, выведите две строки.</p><p>В первой строке выведите целое число $$$d$$$ — минимальное необходимое количество ночей.</p><p>В следующей строке выведите $$$d$$$ целых чисел, где $$$i$$$-е число обозначает количество бактерий, которые поделятся в $$$i$$$-й день.</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 9 11 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 0 2 3 1 1 2 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе, можно получить общую массу бактерий ровно $$$9$$$ следующим образом: </p><ul> <li> День $$$1$$$: Бактерия с массой $$$1$$$ делится. Получаем две бактерии с массой $$$0.5$$$. </li><li> Ночь $$$1$$$: Все бактерии увеличивают массу на один. Получаем две бактерии с массой $$$1.5$$$. </li><li> День $$$2$$$: Ни одна бактерия не делится. </li><li> Ночь $$$2$$$: Получаем две бактерии с массой $$$2.5$$$. </li><li> День $$$3$$$: Обе бактерии делятся. Получаем четыре бактерии с массой $$$1.25$$$. </li><li> Ночь $$$3$$$: Получаем четыре бактерии с массой $$$2.25$$$. </li></ul> Суммарная масса равна $$$2.25+2.25+2.25+2.25=9$$$. Можно доказать, что $$$3$$$ — минимальное необходимое количество ночей. Есть и другие способы добиться суммарной массы 9 за 3 ночи.<p>$$$ $$$</p><p>В втором наборе, можно получить общую массу бактерий ровно $$$11$$$ следующим образом: </p><ul> <li> День $$$1$$$: Бактерия с массой $$$1$$$ делится. Получаем две бактерии с массой $$$0.5$$$. </li><li> Ночь $$$1$$$: Получаем две бактерии с массой $$$1.5$$$. </li><li> День $$$2$$$: Одна бактерия делится. Получаем три бактерии с массами $$$0.75$$$, $$$0.75$$$ и $$$1.5$$$. </li><li> Ночь $$$2$$$: Получаем три бактерии с массами $$$1.75$$$, $$$1.75$$$ и $$$2.5$$$. </li><li> День $$$3$$$: Бактерия с массой $$$1.75$$$ и бактерия с массой $$$2.5$$$ делятся. Получаем пять бактерий с массами $$$0.875$$$, $$$0.875$$$, $$$1.25$$$, $$$1.25$$$ и $$$1.75$$$. </li><li> Ночь $$$3$$$: Получаем пять бактерий с массами $$$1.875$$$, $$$1.875$$$, $$$2.25$$$, $$$2.25$$$ и $$$2.75$$$. </li></ul> Суммарная масса равна $$$1.875+1.875+2.25+2.25+2.75=11$$$. Можно доказать, что $$$3$$$ — минимальное необходимое количество ночей. Есть и другие способы добиться суммарной массы 11 за 3 ночи.<p>$$$ $$$</p><p>Во третьем наборе, бактерия не делится в день $$$1$$$, а потом увеличивает массу до $$$2$$$ в ночь $$$1$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'81249fcd0b563374',t:'MTY5NjY2NTc3MS4xNTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1900"]
1348E
1348
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$$$ кустов, и на каждом кусте созрело $$$a_i$$$ красных ягод и $$$b_i$$$ синих ягод.</p><p>Каждая корзина вмещает $$$k$$$ ягод. Но Феникс решил, что в каждой корзине могут лежать ягоды с одного куста, или же ягоды одного цвета (красные или синие). Другими словами все ягоды в одной корзине должны быть с одного куста и/или одного цвета.</p><p>Например, если у Феникса растет два куста с $$$5$$$ красными и $$$2$$$ синими ягодами на первом кусте и $$$2$$$ красными и $$$1$$$ синей на втором, то он сможет полностью заполнить $$$2$$$ корзины объемом $$$4$$$: </p><ul> <li> в первую корзину он положит $$$3$$$ красные и $$$1$$$ синюю ягоду с первого куста; </li><li> во вторую корзину — $$$2$$$ оставшиеся красные ягоды с первого куста и $$$2$$$ красные ягоды со второго. </li></ul><p>Помогите Фениксу определить максимальное количество корзин, которые он сможет <span class="tex-font-style-bf">заполнить полностью</span>!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$k$$$ ($$$ 1\le n, k \le 500$$$)  — количество кустов и вместимость корзин, соответственно.</p><p>В $$$i$$$-й из следующих $$$n$$$ сток задано два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$0 \le a_i, b_i \le 10^9$$$)  — количество красных и синих ягод на $$$i$$$-м кусте, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число  — максимальное количество корзин, которые Феникс сможет заполнить полностью.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 5 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 5 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 5 2 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 2 1000000000 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый пример описан выше.</p><p>Во втором примере, Феникс может полностью заполнить одну корзину, используя все ягоды с первого (и единственного) куста.</p><p>В третьем примере, Феникс не сможет полностью заполнить ни одной корзины, потому что на каждом кусте меньше $$$5$$$ ягод, всего красных ягод менее $$$5$$$ и всего синих ягод менее $$$5$$$.</p><p>В четвертом примере, Феникс может положить все красные ягоды в корзины, оставив синюю ягоду нетронутой.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="366cda95ac5648e147f4304bc7852b2d"/> <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="82ad588e24c9494a01d2e5060ebb4201beecaa76"/> <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='366cda95ac5648e147f4304bc7852b2d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1348%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='366cda95ac5648e147f4304bc7852b2d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1348">Codeforces Round 638 (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='366cda95ac5648e147f4304bc7852b2d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1348/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='366cda95ac5648e147f4304bc7852b2d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="609092"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='366cda95ac5648e147f4304bc7852b2d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="609092"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76696" title="Codeforces Round #638 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10831" resourceName="Codeforces Round #638 (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/76555" title="Codeforces Round #638 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10842" resourceName="Codeforces Round #638 (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/1348">Задачи</a></li> <li><a href="/contest/1348/submit">Отослать</a></li> <li><a href="/contest/1348/my">Мои посылки</a></li> <li><a href="/contest/1348/status">Статус</a></li> <li><a href="/contest/1348/hacks">Взломы</a></li> <li><a href="/contest/1348/room/1">Комната</a></li> <li><a href="/contest/1348/standings">Положение</a></li> <li><a href="/contest/1348/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_83af7fc222b11aaae327f1eb7cac0f13489494cd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ кустов, и на каждом кусте созрело $$$a_i$$$ красных ягод и $$$b_i$$$ синих ягод.</p><p>Каждая корзина вмещает $$$k$$$ ягод. Но Феникс решил, что в каждой корзине могут лежать ягоды с одного куста, или же ягоды одного цвета (красные или синие). Другими словами все ягоды в одной корзине должны быть с одного куста и/или одного цвета.</p><p>Например, если у Феникса растет два куста с $$$5$$$ красными и $$$2$$$ синими ягодами на первом кусте и $$$2$$$ красными и $$$1$$$ синей на втором, то он сможет полностью заполнить $$$2$$$ корзины объемом $$$4$$$: </p><ul> <li> в первую корзину он положит $$$3$$$ красные и $$$1$$$ синюю ягоду с первого куста; </li><li> во вторую корзину — $$$2$$$ оставшиеся красные ягоды с первого куста и $$$2$$$ красные ягоды со второго. </li></ul><p>Помогите Фениксу определить максимальное количество корзин, которые он сможет <span class="tex-font-style-bf">заполнить полностью</span>!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$k$$$ ($$$ 1\le n, k \le 500$$$)  — количество кустов и вместимость корзин, соответственно.</p><p>В $$$i$$$-й из следующих $$$n$$$ сток задано два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$0 \le a_i, b_i \le 10^9$$$)  — количество красных и синих ягод на $$$i$$$-м кусте, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число  — максимальное количество корзин, которые Феникс сможет заполнить полностью.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 5 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 5 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 5 2 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 2 1000000000 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый пример описан выше.</p><p>Во втором примере, Феникс может полностью заполнить одну корзину, используя все ягоды с первого (и единственного) куста.</p><p>В третьем примере, Феникс не сможет полностью заполнить ни одной корзины, потому что на каждом кусте меньше $$$5$$$ ягод, всего красных ягод менее $$$5$$$ и всего синих ягод менее $$$5$$$.</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 11:02: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:'81249fd588d79d86',t:'MTY5NjY2NTc3Mi41MTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2400"]
1348F
1348
F
ru
F. Феникс и память
<div class="problem-statement"><div class="header"><div class="title">F. Феникс и память</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Феникс хотел сделать фото своих $$$n$$$ друзей, пронумерованных $$$1, 2, \dots, n$$$. Друзья стояли в ряд в некотором порядке. И тут вдруг пришли печенеги с половцами и всех переставили.</p><p>Теперь Фениксу нужно восстановить данный порядок, но он почти ничего не помнит! Все, что Феникс запомнил, — что $$$i$$$-й слева друг имеет номер от $$$a_i$$$ по $$$b_i$$$ включительно. Единственным ли является порядок друзей, подходящий под его воспоминания?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — количество друзей.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк заданы два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i \le b_i \le n$$$) — то, что запомнил Феникс про $$$i$$$-ю позицию слева.</p><p>Гарантируется, что информация, которую запомнил Феникс, не противоречива, и существует хотя бы один подходящий порядок.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если существует единственный подходящий порядок друзей, выведите <span class="tex-font-style-tt">YES</span>, а далее $$$n$$$ целых чисел, где $$$i$$$-е число означает номер $$$i$$$-го слева друга.</p><p>В противном случае, выведите <span class="tex-font-style-tt">NO</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> 4 4 4 1 3 2 4 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 4 1 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 3 2 4 3 4 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO 1 3 4 2 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="c92f2f1e826604f182fe8de057de242f"/> <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="82ad588e24c9494a01d2e5060ebb4201beecaa76"/> <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='c92f2f1e826604f182fe8de057de242f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1348%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='c92f2f1e826604f182fe8de057de242f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1348">Codeforces Round 638 (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='c92f2f1e826604f182fe8de057de242f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1348/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='c92f2f1e826604f182fe8de057de242f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="609093"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c92f2f1e826604f182fe8de057de242f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="609093"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76696" title="Codeforces Round #638 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10831" resourceName="Codeforces Round #638 (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/76555" title="Codeforces Round #638 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10842" resourceName="Codeforces Round #638 (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/1348">Задачи</a></li> <li><a href="/contest/1348/submit">Отослать</a></li> <li><a href="/contest/1348/my">Мои посылки</a></li> <li><a href="/contest/1348/status">Статус</a></li> <li><a href="/contest/1348/hacks">Взломы</a></li> <li><a href="/contest/1348/room/1">Комната</a></li> <li><a href="/contest/1348/standings">Положение</a></li> <li><a href="/contest/1348/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_40b6d6e5187a11f25a4881a98a5240bb410c759f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Феникс и память</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Феникс хотел сделать фото своих $$$n$$$ друзей, пронумерованных $$$1, 2, \dots, n$$$. Друзья стояли в ряд в некотором порядке. И тут вдруг пришли печенеги с половцами и всех переставили.</p><p>Теперь Фениксу нужно восстановить данный порядок, но он почти ничего не помнит! Все, что Феникс запомнил, — что $$$i$$$-й слева друг имеет номер от $$$a_i$$$ по $$$b_i$$$ включительно. Единственным ли является порядок друзей, подходящий под его воспоминания?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — количество друзей.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк заданы два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i \le b_i \le n$$$) — то, что запомнил Феникс про $$$i$$$-ю позицию слева.</p><p>Гарантируется, что информация, которую запомнил Феникс, не противоречива, и существует хотя бы один подходящий порядок.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если существует единственный подходящий порядок друзей, выведите <span class="tex-font-style-tt">YES</span>, а далее $$$n$$$ целых чисел, где $$$i$$$-е число означает номер $$$i$$$-го слева друга.</p><p>В противном случае, выведите <span class="tex-font-style-tt">NO</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> 4 4 4 1 3 2 4 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 4 1 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 3 2 4 3 4 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO 1 3 4 2 1 2 4 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 11:02: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:'81249fddea6816df',t:'MTY5NjY2NTc3My44OTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2600"]
1349A
1349
A
ru
A. Орак и LCM
<div class="problem-statement"><div class="header"><div class="title">A. Орак и LCM</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для мультимножества натуральных чисел $$$s=\{s_1,s_2,\dots,s_k\}$$$, определим наименьшее общее кратное («<span class="tex-font-style-tt">LCM</span>» по-английски) и наибольший общий делитель («<span class="tex-font-style-tt">GCD</span>» по-английски) $$$s$$$ следующим образом:</p><ul><li> $$$\gcd(s)$$$ это максимальное натуральное число $$$x$$$, такое что все числа из $$$s$$$ делятся на $$$x$$$.</li><li> $$$\textrm{lcm}(s)$$$ это минимальное натуральное число $$$x$$$, которое делится на все числа из $$$s$$$.</li></ul><p>Например, $$$\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$$$ и $$$\textrm{lcm}(\{4,6\})=12$$$. Обратите внимание, что для любого натурального числа $$$x$$$, $$$\gcd(\{x\})=\textrm{lcm}(\{x\})=x$$$.</p><p>У Орака есть последовательность $$$a$$$ длины $$$n$$$. Он придумал мультимножество $$$t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i&lt;j\}$$$ и попросил вас найти $$$\gcd(t)$$$ для него. Иначе говоря, вам нужно найти НОД НОКов всех пар элементов в данной последовательности.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (2\le n\le 100\,000)$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 200\,000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: $$$\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i&lt;j\})$$$.</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 10 24 40 80 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 40 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 540 648 810 648 720 540 594 864 972 648 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 54 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$t=\{\textrm{lcm}(\{1,1\})\}=\{1\}$$$, и $$$\gcd(t)=1$$$.</p><p>Во втором примере $$$t=\{120,40,80,120,240,80\}$$$. Нетрудно видеть, что $$$\gcd(t)=40$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="2c56c9598db1b53cdd610fcff31e7d9d"/> <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="e5d0d54fcaf97d82ec82f9dee38573ec72e953be"/> <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='2c56c9598db1b53cdd610fcff31e7d9d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1349%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='2c56c9598db1b53cdd610fcff31e7d9d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1349">Codeforces Round 641 (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='2c56c9598db1b53cdd610fcff31e7d9d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1349/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='2c56c9598db1b53cdd610fcff31e7d9d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619059"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2c56c9598db1b53cdd610fcff31e7d9d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619059"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10868" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10877" resourceName="Codeforces Round #641 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/1349">Задачи</a></li> <li><a href="/contest/1349/submit">Отослать</a></li> <li><a href="/contest/1349/my">Мои посылки</a></li> <li><a href="/contest/1349/status">Статус</a></li> <li><a href="/contest/1349/hacks">Взломы</a></li> <li><a href="/contest/1349/room/1">Комната</a></li> <li><a href="/contest/1349/standings">Положение</a></li> <li><a href="/contest/1349/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d767aa96b6b9acea107aac346029b3f4b09c4ba3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Орак и LCM</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для мультимножества натуральных чисел $$$s=\{s_1,s_2,\dots,s_k\}$$$, определим наименьшее общее кратное («<span class="tex-font-style-tt">LCM</span>» по-английски) и наибольший общий делитель («<span class="tex-font-style-tt">GCD</span>» по-английски) $$$s$$$ следующим образом:</p><ul><li> $$$\gcd(s)$$$ это максимальное натуральное число $$$x$$$, такое что все числа из $$$s$$$ делятся на $$$x$$$.</li><li> $$$\textrm{lcm}(s)$$$ это минимальное натуральное число $$$x$$$, которое делится на все числа из $$$s$$$.</li></ul><p>Например, $$$\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$$$ и $$$\textrm{lcm}(\{4,6\})=12$$$. Обратите внимание, что для любого натурального числа $$$x$$$, $$$\gcd(\{x\})=\textrm{lcm}(\{x\})=x$$$.</p><p>У Орака есть последовательность $$$a$$$ длины $$$n$$$. Он придумал мультимножество $$$t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i&lt;j\}$$$ и попросил вас найти $$$\gcd(t)$$$ для него. Иначе говоря, вам нужно найти НОД НОКов всех пар элементов в данной последовательности.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (2\le n\le 100\,000)$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 200\,000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: $$$\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i&lt;j\})$$$.</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 10 24 40 80 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 40 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 540 648 810 648 720 540 594 864 972 648 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 54 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$t=\{\textrm{lcm}(\{1,1\})\}=\{1\}$$$, и $$$\gcd(t)=1$$$.</p><p>Во втором примере $$$t=\{120,40,80,120,240,80\}$$$. Нетрудно видеть, что $$$\gcd(t)=40$$$.</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 11:02: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:'81249fe679c816e8',t:'MTY5NjY2NTc3NS4zMjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"]
1349B
1349
B
ru
B. Орак и медианы
<div class="problem-statement"><div class="header"><div class="title">B. Орак и медианы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Слайма есть последовательность натуральных чисел $$$a_1, a_2, \ldots, a_n$$$.</p><p>За одну операцию Орак может выбрать произвольный отрезок $$$[l \ldots r]$$$ этой последовательности и заменить все числа $$$a_l, a_{l + 1}, \ldots, a_r$$$ на значение медианы $$$\{a_l, a_{l + 1}, \ldots, a_r\}$$$.</p><p>В этой задаче для мультимножества натуральных чисел $$$s$$$, медиана $$$s$$$ равна $$$\lfloor \frac{|s|+1}{2}\rfloor$$$-у числу в порядке возрастания в нем. Например, медиана $$$\{1,4,4,6,5\}$$$ равна $$$4$$$, а медиана $$$\{1,7,5,8\}$$$ равна $$$5$$$.</p><p>Слайм хочет, чтобы Орак добился $$$a_1 = a_2 = \ldots = a_n = k$$$ с помощью этих операций.</p><p>Орак думает, что это невозможно, и он не хочет тратить свое время, поэтому он решил спросить вас, можно ли исполнить желание Слайма, и он может задавать вам запросы такого вида несколько раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$: количество запросов.</p><p>В первой строке каждого запроса записано два целых числа $$$n\ (1\le n\le 100\,000)$$$ и $$$k\ (1\le k\le 10^9)$$$, во второй строке записаны $$$n$$$ натуральных чисел $$$a_1,a_2,\dots,a_n\ (1\le a_i\le 10^9)$$$</p><p>Сумма $$$n$$$ по всем запросам не превосходит $$$100\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$t$$$ строк. В $$$i$$$-й из них должно быть записано '<span class="tex-font-style-tt">yes</span>', если возможно превратить все числа в $$$k$$$ за какое-нибудь число операций или '<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 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> no yes yes no yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе Орак не может превратить все элементы в $$$3$$$.</p><p>Во втором запросе $$$a_1=6$$$ уже выполнено.</p><p>В третьем запросе Орак может для операции выбрать весь массив и превратить его в $$$2$$$.</p><p>В четвертом запросе Орак не может превратить все элементы в $$$3$$$.</p><p>В пятом запросе Орак может сначала выбрать $$$[1,6]$$$, а затем $$$[2,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="94a2e92ba990fc719b443c2cf303fde1"/> <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="e5d0d54fcaf97d82ec82f9dee38573ec72e953be"/> <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='94a2e92ba990fc719b443c2cf303fde1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1349%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='94a2e92ba990fc719b443c2cf303fde1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1349">Codeforces Round 641 (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='94a2e92ba990fc719b443c2cf303fde1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1349/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='94a2e92ba990fc719b443c2cf303fde1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619060"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='94a2e92ba990fc719b443c2cf303fde1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619060"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10868" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10877" resourceName="Codeforces Round #641 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/1349">Задачи</a></li> <li><a href="/contest/1349/submit">Отослать</a></li> <li><a href="/contest/1349/my">Мои посылки</a></li> <li><a href="/contest/1349/status">Статус</a></li> <li><a href="/contest/1349/hacks">Взломы</a></li> <li><a href="/contest/1349/room/1">Комната</a></li> <li><a href="/contest/1349/standings">Положение</a></li> <li><a href="/contest/1349/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b8c19a985974ccd2b5c7919b247cb12ea83c9624"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Орак и медианы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Слайма есть последовательность натуральных чисел $$$a_1, a_2, \ldots, a_n$$$.</p><p>За одну операцию Орак может выбрать произвольный отрезок $$$[l \ldots r]$$$ этой последовательности и заменить все числа $$$a_l, a_{l + 1}, \ldots, a_r$$$ на значение медианы $$$\{a_l, a_{l + 1}, \ldots, a_r\}$$$.</p><p>В этой задаче для мультимножества натуральных чисел $$$s$$$, медиана $$$s$$$ равна $$$\lfloor \frac{|s|+1}{2}\rfloor$$$-у числу в порядке возрастания в нем. Например, медиана $$$\{1,4,4,6,5\}$$$ равна $$$4$$$, а медиана $$$\{1,7,5,8\}$$$ равна $$$5$$$.</p><p>Слайм хочет, чтобы Орак добился $$$a_1 = a_2 = \ldots = a_n = k$$$ с помощью этих операций.</p><p>Орак думает, что это невозможно, и он не хочет тратить свое время, поэтому он решил спросить вас, можно ли исполнить желание Слайма, и он может задавать вам запросы такого вида несколько раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$: количество запросов.</p><p>В первой строке каждого запроса записано два целых числа $$$n\ (1\le n\le 100\,000)$$$ и $$$k\ (1\le k\le 10^9)$$$, во второй строке записаны $$$n$$$ натуральных чисел $$$a_1,a_2,\dots,a_n\ (1\le a_i\le 10^9)$$$</p><p>Сумма $$$n$$$ по всем запросам не превосходит $$$100\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$t$$$ строк. В $$$i$$$-й из них должно быть записано '<span class="tex-font-style-tt">yes</span>', если возможно превратить все числа в $$$k$$$ за какое-нибудь число операций или '<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 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> no yes yes no yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе Орак не может превратить все элементы в $$$3$$$.</p><p>Во втором запросе $$$a_1=6$$$ уже выполнено.</p><p>В третьем запросе Орак может для операции выбрать весь массив и превратить его в $$$2$$$.</p><p>В четвертом запросе Орак не может превратить все элементы в $$$3$$$.</p><p>В пятом запросе Орак может сначала выбрать $$$[1,6]$$$, а затем $$$[2,10]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:02: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:'81249fef6e6a7b43',t:'MTY5NjY2NTc3Ni42NzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2000"]
1349C
1349
C
ru
C. Орак и Game of Life
<div class="problem-statement"><div class="header"><div class="title">C. Орак и Game of Life</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>128 мегабайт</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-tt">Game of Life</span>».</p><p>Вы должны играть в эту игру на черно-белом клетчатом поле из $$$n$$$ строк и $$$m$$$ столбцов. Каждая клетка либо белая, либо черная. </p><p>На каждой итерации этой игры (исходная итерация это $$$0$$$) цвет клетки будет изменяться по следующим правилам:</p><ul><li> Если на текущей итерации нет соседних клеток с таким же цветом, как и эта клетка, ее цвет на следующей итерации останется прежним.</li><li> Иначе, ее цвет на следующей итерации будет другим.</li></ul><p>Две клетки являются соседними, если у них есть общая сторона.</p><p>Орак уже выбрал исходное состояние игры, и он хочет знать для клетки $$$(i,j)$$$ (в $$$i$$$-й строке и $$$j$$$-м столбце), чему будет равен ее цвет на итерации $$$p$$$. Он может задавать вам эти вопросы по несколько раз. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано три целых числа $$$n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)$$$, описывающие количество строк и столбцов, и количество запросов Орака.</p><p>Каждая из следующих $$$n$$$ строк содержит бинарную строку длины $$$m$$$, $$$j$$$-й символ в $$$i$$$-й строке описывает изначальный цвет клетки $$$(i,j)$$$. '<span class="tex-font-style-tt">0</span>' означает белый, '<span class="tex-font-style-tt">1</span>' означает черный.</p><p>Каждая из следующих $$$t$$$ строк содержит три целых числа $$$i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})$$$, описывающие запрос Орака.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, в $$$i$$$-й из которых вы должны вывести ответ на $$$i$$$-й запрос Орака. Если цвет клетки черный, вы должны вывести '<span class="tex-font-style-tt">1</span>', иначе, вы должны вывести '<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 3 3 000 111 000 1 1 1 2 2 2 3 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 01 10 01 10 01 1 1 4 5 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 3 01011 10110 01101 11010 10101 1 1 4 1 2 3 5 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 3 0 1 1 1 1 1 2 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/eeb42d9bfc2462ba84fcfac9bf8c45511650f63f.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В первом примере картинка выше описывает исходну ситуацию и цвета клеток на итерациях $$$1$$$, $$$2$$$, и $$$3$$$. Вы можете увидеть, что цвет клетки $$$(1,1)$$$ на итерации $$$1$$$ черный, цвет клетки $$$(2,2)$$$ после итерации $$$2$$$ черный, и цвет клетки $$$(3,3)$$$ после итерации $$$3$$$ тоже черный.</p><p>Во втором примере можно доказать, что клетки никогда не поменяют свой цвет.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4c7bb9a306e840c3fe539ee9f817978f"/> <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="e5d0d54fcaf97d82ec82f9dee38573ec72e953be"/> <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='4c7bb9a306e840c3fe539ee9f817978f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1349%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='4c7bb9a306e840c3fe539ee9f817978f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1349">Codeforces Round 641 (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='4c7bb9a306e840c3fe539ee9f817978f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1349/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='4c7bb9a306e840c3fe539ee9f817978f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619061"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4c7bb9a306e840c3fe539ee9f817978f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619061"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10868" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10877" resourceName="Codeforces Round #641 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/1349">Задачи</a></li> <li><a href="/contest/1349/submit">Отослать</a></li> <li><a href="/contest/1349/my">Мои посылки</a></li> <li><a href="/contest/1349/status">Статус</a></li> <li><a href="/contest/1349/hacks">Взломы</a></li> <li><a href="/contest/1349/room/1">Комната</a></li> <li><a href="/contest/1349/standings">Положение</a></li> <li><a href="/contest/1349/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b892ad9d2ab0d8d9ca55f83ebe66a13de5c7e50a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Орак и Game of Life</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>128 мегабайт</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-tt">Game of Life</span>».</p><p>Вы должны играть в эту игру на черно-белом клетчатом поле из $$$n$$$ строк и $$$m$$$ столбцов. Каждая клетка либо белая, либо черная. </p><p>На каждой итерации этой игры (исходная итерация это $$$0$$$) цвет клетки будет изменяться по следующим правилам:</p><ul><li> Если на текущей итерации нет соседних клеток с таким же цветом, как и эта клетка, ее цвет на следующей итерации останется прежним.</li><li> Иначе, ее цвет на следующей итерации будет другим.</li></ul><p>Две клетки являются соседними, если у них есть общая сторона.</p><p>Орак уже выбрал исходное состояние игры, и он хочет знать для клетки $$$(i,j)$$$ (в $$$i$$$-й строке и $$$j$$$-м столбце), чему будет равен ее цвет на итерации $$$p$$$. Он может задавать вам эти вопросы по несколько раз. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано три целых числа $$$n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)$$$, описывающие количество строк и столбцов, и количество запросов Орака.</p><p>Каждая из следующих $$$n$$$ строк содержит бинарную строку длины $$$m$$$, $$$j$$$-й символ в $$$i$$$-й строке описывает изначальный цвет клетки $$$(i,j)$$$. '<span class="tex-font-style-tt">0</span>' означает белый, '<span class="tex-font-style-tt">1</span>' означает черный.</p><p>Каждая из следующих $$$t$$$ строк содержит три целых числа $$$i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})$$$, описывающие запрос Орака.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, в $$$i$$$-й из которых вы должны вывести ответ на $$$i$$$-й запрос Орака. Если цвет клетки черный, вы должны вывести '<span class="tex-font-style-tt">1</span>', иначе, вы должны вывести '<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 3 3 000 111 000 1 1 1 2 2 2 3 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 01 10 01 10 01 1 1 4 5 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 3 01011 10110 01101 11010 10101 1 1 4 1 2 3 5 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 3 0 1 1 1 1 1 2 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/eeb42d9bfc2462ba84fcfac9bf8c45511650f63f.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В первом примере картинка выше описывает исходну ситуацию и цвета клеток на итерациях $$$1$$$, $$$2$$$, и $$$3$$$. Вы можете увидеть, что цвет клетки $$$(1,1)$$$ на итерации $$$1$$$ черный, цвет клетки $$$(2,2)$$$ после итерации $$$2$$$ черный, и цвет клетки $$$(3,3)$$$ после итерации $$$3$$$ тоже черный.</p><p>Во втором примере можно доказать, что клетки никогда не поменяют свой цвет.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'81249ff7fad17a64',t:'MTY5NjY2NTc3OC4wMDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2000"]
1349D
1349
D
ru
D. Слайм и бисквиты
<div class="problem-statement"><div class="header"><div class="title">D. Слайм и бисквиты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Слайм и его $$$n$$$ друзей на вечеринке. Слайм придумал игру для своих друзей.</p><p>В начале игры у $$$i$$$-го игрока есть $$$a_i$$$ бисквитов. Каждую секунду Слайм выберет один бисквит равновероятно среди $$$a_1 + a_2 + \ldots + a_n$$$ бисквитов, и владелец этого бисквита передает его случайному игроку, равновероятно среди $$$n-1$$$ игроков кроме себя. Игра закончится, когда у одного игрока будут все бисквиты.</p><p>Как хозяин вечеринки, Слайм хочет узнать математическое ожидание времени, когда игра закончится, чтобы успеть провести следующее мероприятие.</p><p>Так как ответ может быть представлен в виде рациональной дроби $$$\frac{p}{q}$$$ для взаимно простых $$$p$$$ и $$$q$$$, выведите его в форме $$$(p \cdot q^{-1})\mod 998\,244\,353$$$. Можно доказать, что $$$q\mod 998\,244\,353 \neq 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (2\le n\le 100\,000)$$$: количество игроков.</p><p>Во второй строке записаны $$$n$$$ неотрицательных целых чисел $$$a_1,a_2,\dots,a_n\ (1\le a_1+a_2+\dots+a_n\le 300\,000)$$$, где $$$a_i$$$ обозначает количество бисквитов у $$$i$$$-го человека в начале игры.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число: математическое ожидание времени, когда игра закончится, по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 0 0 0 35 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 8 4 2 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 801604029 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вероятность, что игрок $$$1$$$ передаст игроку $$$2$$$ бисквит равна $$$\frac{1}{2}$$$, а вероятность что игрок $$$2$$$ передаст игроку $$$1$$$ бисквит равна $$$\frac{1}{2}$$$. В любом случае игра продлится ровно $$$1$$$ секунду, так как все бисквиты будут у одного игрока спустя $$$1$$$ секунду, поэтому ответ равен $$$1$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="be63738a3f65118fb13e99e5c2b445dd"/> <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="e5d0d54fcaf97d82ec82f9dee38573ec72e953be"/> <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='be63738a3f65118fb13e99e5c2b445dd'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1349%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='be63738a3f65118fb13e99e5c2b445dd'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1349">Codeforces Round 641 (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='be63738a3f65118fb13e99e5c2b445dd'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1349/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound 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='be63738a3f65118fb13e99e5c2b445dd'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619062"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='be63738a3f65118fb13e99e5c2b445dd'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619062"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10868" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10877" resourceName="Codeforces Round #641 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/1349">Задачи</a></li> <li><a href="/contest/1349/submit">Отослать</a></li> <li><a href="/contest/1349/my">Мои посылки</a></li> <li><a href="/contest/1349/status">Статус</a></li> <li><a href="/contest/1349/hacks">Взломы</a></li> <li><a href="/contest/1349/room/1">Комната</a></li> <li><a href="/contest/1349/standings">Положение</a></li> <li><a href="/contest/1349/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d0528aca95094fc63590abb571b27876e0833343"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Слайм и бисквиты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Слайм и его $$$n$$$ друзей на вечеринке. Слайм придумал игру для своих друзей.</p><p>В начале игры у $$$i$$$-го игрока есть $$$a_i$$$ бисквитов. Каждую секунду Слайм выберет один бисквит равновероятно среди $$$a_1 + a_2 + \ldots + a_n$$$ бисквитов, и владелец этого бисквита передает его случайному игроку, равновероятно среди $$$n-1$$$ игроков кроме себя. Игра закончится, когда у одного игрока будут все бисквиты.</p><p>Как хозяин вечеринки, Слайм хочет узнать математическое ожидание времени, когда игра закончится, чтобы успеть провести следующее мероприятие.</p><p>Так как ответ может быть представлен в виде рациональной дроби $$$\frac{p}{q}$$$ для взаимно простых $$$p$$$ и $$$q$$$, выведите его в форме $$$(p \cdot q^{-1})\mod 998\,244\,353$$$. Можно доказать, что $$$q\mod 998\,244\,353 \neq 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (2\le n\le 100\,000)$$$: количество игроков.</p><p>Во второй строке записаны $$$n$$$ неотрицательных целых чисел $$$a_1,a_2,\dots,a_n\ (1\le a_1+a_2+\dots+a_n\le 300\,000)$$$, где $$$a_i$$$ обозначает количество бисквитов у $$$i$$$-го человека в начале игры.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число: математическое ожидание времени, когда игра закончится, по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 0 0 0 35 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 8 4 2 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 801604029 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вероятность, что игрок $$$1$$$ передаст игроку $$$2$$$ бисквит равна $$$\frac{1}{2}$$$, а вероятность что игрок $$$2$$$ передаст игроку $$$1$$$ бисквит равна $$$\frac{1}{2}$$$. В любом случае игра продлится ровно $$$1$$$ секунду, так как все бисквиты будут у одного игрока спустя $$$1$$$ секунду, поэтому ответ равен $$$1$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:02: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:'8124a0003abf7b3f',t:'MTY5NjY2NTc3OS40MjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3200"]
1349E
1349
E
ru
E. Слайм и шляпы
<div class="problem-statement"><div class="header"><div class="title">E. Слайм и шляпы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Слайм и Орак проводят пошаговую игру. В большой комнате на стульях сидят $$$n$$$ человек и смотрят в сторону колонны, у каждого игрока есть номер: игрок $$$1$$$ сидит перед колонной, игрок $$$2$$$ сидит прямо за ним; игрок $$$3$$$ сидит прямо за игроком номер $$$2$$$, и так далее; игрок $$$n$$$ сидит прямо за игроком $$$n-1$$$. Каждый игрок носит шляпу, которая может быть белой или черной. Так как все игроки смотрят вперед, игрок $$$i$$$ знает цвет шляпы игрока $$$j$$$ если и только если $$$i$$$ больше чем $$$j$$$.</p><p>В начале каждого хода, Орак скажет, <span class="tex-font-style-bf">есть ли хотя бы один игрок в комнате, на котором надета черная шляпа</span>.</p><p>После речи Орака, если игрок может однозначно определить цвет его шляпы, он положит его шляпу на стул, встанет, и покинет комнату. Все игроки умные, так что если возможно понять цвет шляпы, используя полученную информацию в этом и предыдущих раундах, они поймут.</p><p>На каждом ходу все игроки, которые поняли свой цвет, выйдут одновременно. Это означает, что если игрок понял цвет своей шляпы после ухода игроков на этом ходу, он сможет покинуть комнату только на следующем ходу.</p><p>Обратите внимание, что когда игрок выходит из комнаты, он оставлят свою шляпу на стуле, так что игроки перед ним не смогут узнать цвет его шляпы.</p><p>Таким образом, $$$i$$$-й игрок узнает, кто покинул комнату среди игроков $$$1,2,\ldots,i-1$$$, и сколько игроков среди $$$i+1,i+2,\ldots,n$$$ покинули комнату.</p><p>Слайм стоит за дверью. Он наблюдает за игроками и записывает номера игроков и время, в которое они покинули комнату. К сожалению, Слайм такой неряха, что он записал это только про некоторых игроков и записал он это в формате «<span class="tex-font-style-tt">игрок $$$x$$$ покинул игру в $$$y$$$-м раунде</span>».</p><p>Слайм попросил вас найти цвет шляпы каждого игрока. Если есть несколько возможных решений, вы можете вывести любое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (1\le n\le 200\,000)$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$t_1,t_2,\dots,t_n\ (0\le t_i\le 10^{15})$$$. Если $$$t_i=0$$$, то неизвестна никакая информация про игрока с номером $$$i$$$; иначе, игрок $$$i$$$ покинул игру на $$$t_i$$$-м раунде.</p><p>Хотя бы одно решение существует для данного ввода.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одну бинарную строку из $$$n$$$ символов. $$$i$$$-й символ должен быть равен '<span class="tex-font-style-tt">1</span>' если игрок $$$i$$$ носит черную шляпу, и должен быть равен '<span class="tex-font-style-tt">0</span>' иначе. Если есть несколько решений, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 1 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00000</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 2 2 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00001</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 0 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00000</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 4 0 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00100</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере в предложенном решении, все игроки носят белую шляпу. На первом ходу Орак скажет, что нет игроков с черной шляпой, так что все игроки поймут, что они носят белые шляпы, и покинут игру на первом ходу.</p><p>Во втором примере игрок $$$5$$$ носит черную шляпу, а остальные игроки носят белые шляпы. Орак скажет, что существует игрок в черной шляпе, и игрок $$$5$$$ знает, что все остальные игроки носят белые шляпы, следовательно он может понять, что он носит черную шляпу, и покинет игру в первом раунде, а остальные игроки покинут игру во втором раунде. Обратите внимание, что все игроки поняли цвет шляпы после того, как игрок $$$5$$$ ушел, но они должны ждать следующего хода, чтобы уйти.</p><p>В третьем примере нет никакой информации об игре, так что любой ответ корректен.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4805222c9e519baaff3598e9ce9ddc4e"/> <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="e5d0d54fcaf97d82ec82f9dee38573ec72e953be"/> <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='4805222c9e519baaff3598e9ce9ddc4e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1349%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='4805222c9e519baaff3598e9ce9ddc4e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1349">Codeforces Round 641 (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='4805222c9e519baaff3598e9ce9ddc4e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1349/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='4805222c9e519baaff3598e9ce9ddc4e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619063"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4805222c9e519baaff3598e9ce9ddc4e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619063"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10868" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10877" resourceName="Codeforces Round #641 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/1349">Задачи</a></li> <li><a href="/contest/1349/submit">Отослать</a></li> <li><a href="/contest/1349/my">Мои посылки</a></li> <li><a href="/contest/1349/status">Статус</a></li> <li><a href="/contest/1349/hacks">Взломы</a></li> <li><a href="/contest/1349/room/1">Комната</a></li> <li><a href="/contest/1349/standings">Положение</a></li> <li><a href="/contest/1349/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e7f7ce59888e4e935a047d8b0c90999ff4a3638b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Слайм и шляпы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Слайм и Орак проводят пошаговую игру. В большой комнате на стульях сидят $$$n$$$ человек и смотрят в сторону колонны, у каждого игрока есть номер: игрок $$$1$$$ сидит перед колонной, игрок $$$2$$$ сидит прямо за ним; игрок $$$3$$$ сидит прямо за игроком номер $$$2$$$, и так далее; игрок $$$n$$$ сидит прямо за игроком $$$n-1$$$. Каждый игрок носит шляпу, которая может быть белой или черной. Так как все игроки смотрят вперед, игрок $$$i$$$ знает цвет шляпы игрока $$$j$$$ если и только если $$$i$$$ больше чем $$$j$$$.</p><p>В начале каждого хода, Орак скажет, <span class="tex-font-style-bf">есть ли хотя бы один игрок в комнате, на котором надета черная шляпа</span>.</p><p>После речи Орака, если игрок может однозначно определить цвет его шляпы, он положит его шляпу на стул, встанет, и покинет комнату. Все игроки умные, так что если возможно понять цвет шляпы, используя полученную информацию в этом и предыдущих раундах, они поймут.</p><p>На каждом ходу все игроки, которые поняли свой цвет, выйдут одновременно. Это означает, что если игрок понял цвет своей шляпы после ухода игроков на этом ходу, он сможет покинуть комнату только на следующем ходу.</p><p>Обратите внимание, что когда игрок выходит из комнаты, он оставлят свою шляпу на стуле, так что игроки перед ним не смогут узнать цвет его шляпы.</p><p>Таким образом, $$$i$$$-й игрок узнает, кто покинул комнату среди игроков $$$1,2,\ldots,i-1$$$, и сколько игроков среди $$$i+1,i+2,\ldots,n$$$ покинули комнату.</p><p>Слайм стоит за дверью. Он наблюдает за игроками и записывает номера игроков и время, в которое они покинули комнату. К сожалению, Слайм такой неряха, что он записал это только про некоторых игроков и записал он это в формате «<span class="tex-font-style-tt">игрок $$$x$$$ покинул игру в $$$y$$$-м раунде</span>».</p><p>Слайм попросил вас найти цвет шляпы каждого игрока. Если есть несколько возможных решений, вы можете вывести любое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (1\le n\le 200\,000)$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$t_1,t_2,\dots,t_n\ (0\le t_i\le 10^{15})$$$. Если $$$t_i=0$$$, то неизвестна никакая информация про игрока с номером $$$i$$$; иначе, игрок $$$i$$$ покинул игру на $$$t_i$$$-м раунде.</p><p>Хотя бы одно решение существует для данного ввода.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одну бинарную строку из $$$n$$$ символов. $$$i$$$-й символ должен быть равен '<span class="tex-font-style-tt">1</span>' если игрок $$$i$$$ носит черную шляпу, и должен быть равен '<span class="tex-font-style-tt">0</span>' иначе. Если есть несколько решений, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 1 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00000</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 2 2 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00001</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 0 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00000</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 4 0 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 00100</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере в предложенном решении, все игроки носят белую шляпу. На первом ходу Орак скажет, что нет игроков с черной шляпой, так что все игроки поймут, что они носят белые шляпы, и покинут игру на первом ходу.</p><p>Во втором примере игрок $$$5$$$ носит черную шляпу, а остальные игроки носят белые шляпы. Орак скажет, что существует игрок в черной шляпе, и игрок $$$5$$$ знает, что все остальные игроки носят белые шляпы, следовательно он может понять, что он носит черную шляпу, и покинет игру в первом раунде, а остальные игроки покинут игру во втором раунде. Обратите внимание, что все игроки поняли цвет шляпы после того, как игрок $$$5$$$ ушел, но они должны ждать следующего хода, чтобы уйти.</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 11:03: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:'8124a0091d5716b3',t:'MTY5NjY2NTc4MC43NzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\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\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*3500"]
1349F1
1349
F1
ru
F1. Слайм и последовательности (упрощенная версия)
<div class="problem-statement"><div class="header"><div class="title">F1. Слайм и последовательности (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Обратите внимание что единственные различия между версиями это $$$n$$$ и ограничения по времени. Вы можете взламывать, только если обе версии решены.</span></p><p>Слайм интересуется последовательностями. Он определил <span class="tex-font-style-bf">хорошие</span> последовательности $$$p$$$ длины $$$n$$$ из натуральных чисел следующим образом:</p><ul><li> Для каждого $$$k&gt;1$$$, которое встречается в $$$p$$$, должна существовать хотя бы одна пара индексов $$$i,j$$$, такая что $$$1 \leq i &lt; j \leq n$$$, $$$p_i = k - 1$$$ и $$$p_j = k$$$.</li></ul><p>Для данного целого числа $$$n$$$ множество хороших последовательностей длины $$$n$$$ это $$$s_n$$$. Для фиксированного целого числа $$$k$$$ и последовательности $$$p$$$, обозначим за $$$f_p(k)$$$ количество раз, которое $$$k$$$ встречается в $$$p$$$. Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$, Слайм хочет знать следующее значение:</p><p>$$$$$$\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (1\le n\le 5000)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, $$$i$$$-е из них должно быть равно $$$\left(\sum_{p\in s_n} f_p(i)\right)\ \textrm{mod}\ 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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 7 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$s=\{[1,1],[1,2]\}$$$.</p><p>Во втором примере $$$s=\{[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,2],[1,2,3]\}$$$.</p><p>В третьем примере $$$s=\{[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="02ad69e899368a9dca15763670057bdf"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="e5d0d54fcaf97d82ec82f9dee38573ec72e953be"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='02ad69e899368a9dca15763670057bdf'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1349%2Fproblem%2FF1%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='02ad69e899368a9dca15763670057bdf'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1349">Codeforces Round 641 (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='02ad69e899368a9dca15763670057bdf'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1349/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье"> бпф </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='02ad69e899368a9dca15763670057bdf'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619064"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='02ad69e899368a9dca15763670057bdf'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619064"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10868" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10877" resourceName="Codeforces Round #641 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/1349">Задачи</a></li> <li><a href="/contest/1349/submit">Отослать</a></li> <li><a href="/contest/1349/my">Мои посылки</a></li> <li><a href="/contest/1349/status">Статус</a></li> <li><a href="/contest/1349/hacks">Взломы</a></li> <li><a href="/contest/1349/room/1">Комната</a></li> <li><a href="/contest/1349/standings">Положение</a></li> <li><a href="/contest/1349/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="F1" data-uuid="ps_ce09a34cb97a9a20b7c7e4951174daca1bd27b4a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F1. Слайм и последовательности (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Обратите внимание что единственные различия между версиями это $$$n$$$ и ограничения по времени. Вы можете взламывать, только если обе версии решены.</span></p><p>Слайм интересуется последовательностями. Он определил <span class="tex-font-style-bf">хорошие</span> последовательности $$$p$$$ длины $$$n$$$ из натуральных чисел следующим образом:</p><ul><li> Для каждого $$$k&gt;1$$$, которое встречается в $$$p$$$, должна существовать хотя бы одна пара индексов $$$i,j$$$, такая что $$$1 \leq i &lt; j \leq n$$$, $$$p_i = k - 1$$$ и $$$p_j = k$$$.</li></ul><p>Для данного целого числа $$$n$$$ множество хороших последовательностей длины $$$n$$$ это $$$s_n$$$. Для фиксированного целого числа $$$k$$$ и последовательности $$$p$$$, обозначим за $$$f_p(k)$$$ количество раз, которое $$$k$$$ встречается в $$$p$$$. Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$, Слайм хочет знать следующее значение:</p><p>$$$$$$\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (1\le n\le 5000)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, $$$i$$$-е из них должно быть равно $$$\left(\sum_{p\in s_n} f_p(i)\right)\ \textrm{mod}\ 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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 7 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$s=\{[1,1],[1,2]\}$$$.</p><p>Во втором примере $$$s=\{[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,2],[1,2,3]\}$$$.</p><p>В третьем примере $$$s=\{[1]\}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:03: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:'8124a0117df77b83',t:'MTY5NjY2NTc4Mi4yNjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3100"]
1349F2
1349
F2
ru
F2. Слайм и последовательности (усложненная версия)
<div class="problem-statement"><div class="header"><div class="title">F2. Слайм и последовательности (усложненная версия)</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">Обратите внимание что единственные различия между версиями это $$$n$$$ и ограничения по времени. Вы можете взламывать, только если обе версии решены.</span></p><p>Слайм интересуется последовательностями. Он определил <span class="tex-font-style-bf">хорошие</span> последовательности $$$p$$$ длины $$$n$$$ из натуральных чисел следующим образом:</p><ul><li> Для каждого $$$k&gt;1$$$, которое встречается в $$$p$$$, должна существовать хотя бы одна пара индексов $$$i,j$$$, такая что $$$1 \leq i &lt; j \leq n$$$, $$$p_i = k - 1$$$ и $$$p_j = k$$$.</li></ul><p>Для данного целого числа $$$n$$$ множество хороших последовательностей длины $$$n$$$ это $$$s_n$$$. Для фиксированного целого числа $$$k$$$ и последовательности $$$p$$$, обозначим за $$$f_p(k)$$$ количество раз, которое $$$k$$$ встречается в $$$p$$$. Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$, Слайм хочет знать следующее значение:</p><p>$$$$$$\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (1\le n\le 100\,000)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, $$$i$$$-е из них должно быть равно $$$\left(\sum_{p\in s_n} f_p(i)\right)\ \textrm{mod}\ 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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 7 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$s=\{[1,1],[1,2]\}$$$.</p><p>Во втором примере $$$s=\{[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,2],[1,2,3]\}$$$.</p><p>В третьем примере $$$s=\{[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="f34e858c8d6760bd50f4f8d19816a9e4"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="e5d0d54fcaf97d82ec82f9dee38573ec72e953be"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f34e858c8d6760bd50f4f8d19816a9e4'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1349%2Fproblem%2FF2%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='f34e858c8d6760bd50f4f8d19816a9e4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1349">Codeforces Round 641 (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='f34e858c8d6760bd50f4f8d19816a9e4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1349/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье"> бпф </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='f34e858c8d6760bd50f4f8d19816a9e4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619065"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f34e858c8d6760bd50f4f8d19816a9e4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619065"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10868" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10877" resourceName="Codeforces Round #641 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/1349">Задачи</a></li> <li><a href="/contest/1349/submit">Отослать</a></li> <li><a href="/contest/1349/my">Мои посылки</a></li> <li><a href="/contest/1349/status">Статус</a></li> <li><a href="/contest/1349/hacks">Взломы</a></li> <li><a href="/contest/1349/room/1">Комната</a></li> <li><a href="/contest/1349/standings">Положение</a></li> <li><a href="/contest/1349/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="F2" data-uuid="ps_0a02fb722cce95d53429d9e95166360e55d5f225"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F2. Слайм и последовательности (усложненная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>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">Обратите внимание что единственные различия между версиями это $$$n$$$ и ограничения по времени. Вы можете взламывать, только если обе версии решены.</span></p><p>Слайм интересуется последовательностями. Он определил <span class="tex-font-style-bf">хорошие</span> последовательности $$$p$$$ длины $$$n$$$ из натуральных чисел следующим образом:</p><ul><li> Для каждого $$$k&gt;1$$$, которое встречается в $$$p$$$, должна существовать хотя бы одна пара индексов $$$i,j$$$, такая что $$$1 \leq i &lt; j \leq n$$$, $$$p_i = k - 1$$$ и $$$p_j = k$$$.</li></ul><p>Для данного целого числа $$$n$$$ множество хороших последовательностей длины $$$n$$$ это $$$s_n$$$. Для фиксированного целого числа $$$k$$$ и последовательности $$$p$$$, обозначим за $$$f_p(k)$$$ количество раз, которое $$$k$$$ встречается в $$$p$$$. Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$, Слайм хочет знать следующее значение:</p><p>$$$$$$\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (1\le n\le 100\,000)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, $$$i$$$-е из них должно быть равно $$$\left(\sum_{p\in s_n} f_p(i)\right)\ \textrm{mod}\ 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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 7 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$s=\{[1,1],[1,2]\}$$$.</p><p>Во втором примере $$$s=\{[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,2],[1,2,3]\}$$$.</p><p>В третьем примере $$$s=\{[1]\}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:03: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:'8124a01afc7a7593',t:'MTY5NjY2NTc4My42NTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3500"]
1350A
1350
A
ru
A. Орак и делители
<div class="problem-statement"><div class="header"><div class="title">A. Орак и делители</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Орак изучает теорию чисел, и его очень заинтересовали свойства делимости.</p><p>Для двух натуральных чисел $$$a$$$ и $$$b$$$, $$$a$$$ является делителем $$$b$$$ если и только если существует такое натуральное число $$$c$$$, что $$$a\cdot c=b$$$.</p><p>Для $$$n \ge 2$$$, обозначим за $$$f(n)$$$ минимальный делитель $$$n$$$, отличный от $$$1$$$.</p><p>Например, $$$f(7)=7,f(10)=2,f(35)=5$$$.</p><p>Для выбранного числа $$$n$$$ Орак решил прибавить $$$f(n)$$$ к $$$n$$$. </p><p>Например, если у него было число $$$n=5$$$, новое значение $$$n$$$ будет равно $$$10$$$. А если у него было число $$$n=6$$$, $$$n$$$ станет равным $$$8$$$.</p><p>Ораку так это понравилось, что он решил проделать подобные операции по несколько раз.</p><p>Для двух положительных чисел $$$n$$$ и $$$k$$$, Орак попросил вас прибавить $$$f(n)$$$ к $$$n$$$ ровно $$$k$$$ раз (обратите внимание, что $$$n$$$ изменяется после каждой операции, соотвественно $$$f(n)$$$ тоже может измениться) и сказать ему итоговое значение $$$n$$$.</p><p>Например, если Орак скажет вам, что $$$n=5$$$ и $$$k=2$$$, сначала вы должны прибавить $$$f(5)=5$$$ к $$$n=5$$$, и новое значение $$$n$$$ станет равным $$$n=10$$$, после этого вы должны прибавить $$$f(10)=2$$$ к $$$10$$$, и новое (и итоговое!) значение $$$n$$$ будет равно $$$12$$$.</p><p>Орак может задавать вам эти вопросы несколько раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t\ (1\le t\le 100)$$$: количество запросов Орака.</p><p>В каждой из следующий $$$t$$$ строк записаны два целых числа $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, описывающие очередной запрос.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$10^6$$$. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, в $$$i$$$-й из которых должно быть записано итоговое значение $$$n$$$ для $$$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 5 1 8 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 12 12 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе $$$n=5$$$ и $$$k=1$$$. Делители $$$5$$$ это $$$1$$$ и $$$5$$$, и минимальный делитель, отличный от $$$1$$$ это $$$5$$$. Соответственно, единственная операция это прибавление $$$f(5)=5$$$ к $$$5$$$, поэтому результат равен $$$10$$$.</p><p>Во втором запросе $$$n=8$$$ и $$$k=2$$$. Делители $$$8$$$ это $$$1,2,4,8$$$, и минимальный из них кроме $$$1$$$ равен $$$2$$$, затем, после одной операции $$$8$$$ превратится в $$$8+(f(8)=2)=10$$$. Делители $$$10$$$ это $$$1,2,5,10$$$, минимальный делитель, отличный от $$$1$$$ это $$$2$$$, поэтому ответ равен $$$10+(f(10)=2)=12$$$.</p><p>В третьем запросе $$$n$$$ изменялось следующим образом: $$$3 \to 6 \to 8 \to 10 \to 12$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="13948f968927f6da4f711a78a5fabe8f"/> <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="2a7eb9afd8de440086ab3af564dd49bf72ea6ae3"/> <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='13948f968927f6da4f711a78a5fabe8f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1350%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='13948f968927f6da4f711a78a5fabe8f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1350">Codeforces Round 641 (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='13948f968927f6da4f711a78a5fabe8f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1350/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='13948f968927f6da4f711a78a5fabe8f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619071"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='13948f968927f6da4f711a78a5fabe8f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619071"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10869" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10878" resourceName="Codeforces Round #641 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/1350">Задачи</a></li> <li><a href="/contest/1350/submit">Отослать</a></li> <li><a href="/contest/1350/my">Мои посылки</a></li> <li><a href="/contest/1350/status">Статус</a></li> <li><a href="/contest/1350/hacks">Взломы</a></li> <li><a href="/contest/1350/room/1">Комната</a></li> <li><a href="/contest/1350/standings">Положение</a></li> <li><a href="/contest/1350/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7a23fcc23e4cec1976b55b15d23d6eabfc6c4a86"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Орак и делители</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Орак изучает теорию чисел, и его очень заинтересовали свойства делимости.</p><p>Для двух натуральных чисел $$$a$$$ и $$$b$$$, $$$a$$$ является делителем $$$b$$$ если и только если существует такое натуральное число $$$c$$$, что $$$a\cdot c=b$$$.</p><p>Для $$$n \ge 2$$$, обозначим за $$$f(n)$$$ минимальный делитель $$$n$$$, отличный от $$$1$$$.</p><p>Например, $$$f(7)=7,f(10)=2,f(35)=5$$$.</p><p>Для выбранного числа $$$n$$$ Орак решил прибавить $$$f(n)$$$ к $$$n$$$. </p><p>Например, если у него было число $$$n=5$$$, новое значение $$$n$$$ будет равно $$$10$$$. А если у него было число $$$n=6$$$, $$$n$$$ станет равным $$$8$$$.</p><p>Ораку так это понравилось, что он решил проделать подобные операции по несколько раз.</p><p>Для двух положительных чисел $$$n$$$ и $$$k$$$, Орак попросил вас прибавить $$$f(n)$$$ к $$$n$$$ ровно $$$k$$$ раз (обратите внимание, что $$$n$$$ изменяется после каждой операции, соотвественно $$$f(n)$$$ тоже может измениться) и сказать ему итоговое значение $$$n$$$.</p><p>Например, если Орак скажет вам, что $$$n=5$$$ и $$$k=2$$$, сначала вы должны прибавить $$$f(5)=5$$$ к $$$n=5$$$, и новое значение $$$n$$$ станет равным $$$n=10$$$, после этого вы должны прибавить $$$f(10)=2$$$ к $$$10$$$, и новое (и итоговое!) значение $$$n$$$ будет равно $$$12$$$.</p><p>Орак может задавать вам эти вопросы несколько раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t\ (1\le t\le 100)$$$: количество запросов Орака.</p><p>В каждой из следующий $$$t$$$ строк записаны два целых числа $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, описывающие очередной запрос.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$10^6$$$. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, в $$$i$$$-й из которых должно быть записано итоговое значение $$$n$$$ для $$$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 5 1 8 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 12 12 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе $$$n=5$$$ и $$$k=1$$$. Делители $$$5$$$ это $$$1$$$ и $$$5$$$, и минимальный делитель, отличный от $$$1$$$ это $$$5$$$. Соответственно, единственная операция это прибавление $$$f(5)=5$$$ к $$$5$$$, поэтому результат равен $$$10$$$.</p><p>Во втором запросе $$$n=8$$$ и $$$k=2$$$. Делители $$$8$$$ это $$$1,2,4,8$$$, и минимальный из них кроме $$$1$$$ равен $$$2$$$, затем, после одной операции $$$8$$$ превратится в $$$8+(f(8)=2)=10$$$. Делители $$$10$$$ это $$$1,2,5,10$$$, минимальный делитель, отличный от $$$1$$$ это $$$2$$$, поэтому ответ равен $$$10+(f(10)=2)=12$$$.</p><p>В третьем запросе $$$n$$$ изменялось следующим образом: $$$3 \to 6 \to 8 \to 10 \to 12$$$.</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 11:03: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:'8124a0239aa69d84',t:'MTY5NjY2NTc4NS4wODMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1350B
1350
B
ru
B. Орак и модели
<div class="problem-statement"><div class="header"><div class="title">B. Орак и модели</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В магазине есть $$$n$$$ моделей, пронумерованных от $$$1$$$ до $$$n$$$, размеры которых равны $$$s_1, s_2, \ldots, s_n$$$.</p><p>Орак купит некоторые из этих моделей и упорядочит их по возрастанию номеров (индексов, а не размеров).</p><p>Орак считает, что полученная расстановка <span class="tex-font-style-bf">красивая</span>, если для любых двух соседних моделей с номерами $$$i_j$$$ и $$$i_{j+1}$$$ (обратите внимание, что $$$i_j &lt; i_{j+1}$$$, так как Орак упорядочил их правильно), $$$i_{j+1}$$$ делится на $$$i_j$$$ и $$$s_{i_j} &lt; s_{i_{j+1}}$$$.</p><p>Например, для $$$6$$$ моделей с размерами $$$\{3, 6, 7, 7, 7, 7\}$$$, он может купить модели с индексами $$$1$$$, $$$2$$$, и $$$6$$$, и полученная расстановка будет красивой. Обратите внимание, что расстановка из одной модели также считается красивой.</p><p>Орак хочет знать, какое наибольше число моделей он может купить, и он может задавать вам эти вопросы по несколько раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t\ (1 \le t\le 100)$$$: количество запросов.</p><p>Каждый запрос состоит из двух строк, в первой из которых записано одно целое число $$$n\ (1\le n\le 100\,000)$$$: количество моделей в магазине, а во второй записаны $$$n$$$ целых чисел $$$s_1,\dots,s_n\ (1\le s_i\le 10^9)$$$: размеры моделей.</p><p>Гарантируется, что сумма величин $$$n$$$ не превосходит $$$100\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, в $$$i$$$-й из которых должно быть записано максимальное число моделей, которое Орак может купить для $$$i$$$-го запроса.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 5 3 4 6 7 1 4 2 3 6 4 9 5 5 4 3 2 1 1 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого запроса, например, Орак может купить модели с индексами $$$2$$$ и $$$4$$$, расстановка которых будет красивой так как $$$4$$$ делится на $$$2$$$ и $$$6$$$ больше, чем $$$3$$$. Рассмотрев остальные варианты, можно легко убедиться, что нет красивой расстановки с более, чем тремя моделями.</p><p>Во втором запросе Орак может купить модели с индексами $$$1$$$, $$$3$$$, и $$$6$$$. Рассмотрев остальные варианты, можно легко убедиться, что нет красивой расстановки с более, чем тремя моделями.</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="373f746e4328438adc7f1becc8fc0bc9"/> <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="2a7eb9afd8de440086ab3af564dd49bf72ea6ae3"/> <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='373f746e4328438adc7f1becc8fc0bc9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1350%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='373f746e4328438adc7f1becc8fc0bc9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1350">Codeforces Round 641 (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='373f746e4328438adc7f1becc8fc0bc9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1350/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='373f746e4328438adc7f1becc8fc0bc9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619072"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='373f746e4328438adc7f1becc8fc0bc9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619072"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10869" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10878" resourceName="Codeforces Round #641 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/1350">Задачи</a></li> <li><a href="/contest/1350/submit">Отослать</a></li> <li><a href="/contest/1350/my">Мои посылки</a></li> <li><a href="/contest/1350/status">Статус</a></li> <li><a href="/contest/1350/hacks">Взломы</a></li> <li><a href="/contest/1350/room/1">Комната</a></li> <li><a href="/contest/1350/standings">Положение</a></li> <li><a href="/contest/1350/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_14153d14031d008eefc36f73d1c9e0b4e10c1a0a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Орак и модели</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В магазине есть $$$n$$$ моделей, пронумерованных от $$$1$$$ до $$$n$$$, размеры которых равны $$$s_1, s_2, \ldots, s_n$$$.</p><p>Орак купит некоторые из этих моделей и упорядочит их по возрастанию номеров (индексов, а не размеров).</p><p>Орак считает, что полученная расстановка <span class="tex-font-style-bf">красивая</span>, если для любых двух соседних моделей с номерами $$$i_j$$$ и $$$i_{j+1}$$$ (обратите внимание, что $$$i_j &lt; i_{j+1}$$$, так как Орак упорядочил их правильно), $$$i_{j+1}$$$ делится на $$$i_j$$$ и $$$s_{i_j} &lt; s_{i_{j+1}}$$$.</p><p>Например, для $$$6$$$ моделей с размерами $$$\{3, 6, 7, 7, 7, 7\}$$$, он может купить модели с индексами $$$1$$$, $$$2$$$, и $$$6$$$, и полученная расстановка будет красивой. Обратите внимание, что расстановка из одной модели также считается красивой.</p><p>Орак хочет знать, какое наибольше число моделей он может купить, и он может задавать вам эти вопросы по несколько раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t\ (1 \le t\le 100)$$$: количество запросов.</p><p>Каждый запрос состоит из двух строк, в первой из которых записано одно целое число $$$n\ (1\le n\le 100\,000)$$$: количество моделей в магазине, а во второй записаны $$$n$$$ целых чисел $$$s_1,\dots,s_n\ (1\le s_i\le 10^9)$$$: размеры моделей.</p><p>Гарантируется, что сумма величин $$$n$$$ не превосходит $$$100\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, в $$$i$$$-й из которых должно быть записано максимальное число моделей, которое Орак может купить для $$$i$$$-го запроса.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 5 3 4 6 7 1 4 2 3 6 4 9 5 5 4 3 2 1 1 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого запроса, например, Орак может купить модели с индексами $$$2$$$ и $$$4$$$, расстановка которых будет красивой так как $$$4$$$ делится на $$$2$$$ и $$$6$$$ больше, чем $$$3$$$. Рассмотрев остальные варианты, можно легко убедиться, что нет красивой расстановки с более, чем тремя моделями.</p><p>Во втором запросе Орак может купить модели с индексами $$$1$$$, $$$3$$$, и $$$6$$$. Рассмотрев остальные варианты, можно легко убедиться, что нет красивой расстановки с более, чем тремя моделями.</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 11:03: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:'8124a02c99da16d3',t:'MTY5NjY2NTc4Ni40MzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1400"]
1350C
1350
C
ru
C. Орак и LCM
<div class="problem-statement"><div class="header"><div class="title">C. Орак и LCM</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для мультимножества натуральных чисел $$$s=\{s_1,s_2,\dots,s_k\}$$$, определим наименьшее общее кратное («<span class="tex-font-style-tt">LCM</span>» по-английски) и наибольший общий делитель («<span class="tex-font-style-tt">GCD</span>» по-английски) $$$s$$$ следующим образом:</p><ul><li> $$$\gcd(s)$$$ это максимальное натуральное число $$$x$$$, такое что все числа из $$$s$$$ делятся на $$$x$$$.</li><li> $$$\textrm{lcm}(s)$$$ это минимальное натуральное число $$$x$$$, которое делится на все числа из $$$s$$$.</li></ul><p>Например, $$$\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$$$ и $$$\textrm{lcm}(\{4,6\})=12$$$. Обратите внимание, что для любого натурального числа $$$x$$$, $$$\gcd(\{x\})=\textrm{lcm}(\{x\})=x$$$.</p><p>У Орака есть последовательность $$$a$$$ длины $$$n$$$. Он придумал мультимножество $$$t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i&lt;j\}$$$ и попросил вас найти $$$\gcd(t)$$$ для него. Иначе говоря, вам нужно найти НОД НОКов всех пар элементов в данной последовательности.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (2\le n\le 100\,000)$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 200\,000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: $$$\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i&lt;j\})$$$.</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 10 24 40 80 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 40 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 540 648 810 648 720 540 594 864 972 648 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 54 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$t=\{\textrm{lcm}(\{1,1\})\}=\{1\}$$$, и $$$\gcd(t)=1$$$.</p><p>Во втором примере $$$t=\{120,40,80,120,240,80\}$$$. Нетрудно видеть, что $$$\gcd(t)=40$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="0a1305eb0a624f8334946093249fbe95"/> <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="2a7eb9afd8de440086ab3af564dd49bf72ea6ae3"/> <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='0a1305eb0a624f8334946093249fbe95'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1350%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='0a1305eb0a624f8334946093249fbe95'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1350">Codeforces Round 641 (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='0a1305eb0a624f8334946093249fbe95'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1350/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='0a1305eb0a624f8334946093249fbe95'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619073"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0a1305eb0a624f8334946093249fbe95'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619073"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10869" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10878" resourceName="Codeforces Round #641 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/1350">Задачи</a></li> <li><a href="/contest/1350/submit">Отослать</a></li> <li><a href="/contest/1350/my">Мои посылки</a></li> <li><a href="/contest/1350/status">Статус</a></li> <li><a href="/contest/1350/hacks">Взломы</a></li> <li><a href="/contest/1350/room/1">Комната</a></li> <li><a href="/contest/1350/standings">Положение</a></li> <li><a href="/contest/1350/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b7828ed8ee56b751364a3ae22f09e7a7f77e42fa"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Орак и LCM</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для мультимножества натуральных чисел $$$s=\{s_1,s_2,\dots,s_k\}$$$, определим наименьшее общее кратное («<span class="tex-font-style-tt">LCM</span>» по-английски) и наибольший общий делитель («<span class="tex-font-style-tt">GCD</span>» по-английски) $$$s$$$ следующим образом:</p><ul><li> $$$\gcd(s)$$$ это максимальное натуральное число $$$x$$$, такое что все числа из $$$s$$$ делятся на $$$x$$$.</li><li> $$$\textrm{lcm}(s)$$$ это минимальное натуральное число $$$x$$$, которое делится на все числа из $$$s$$$.</li></ul><p>Например, $$$\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$$$ и $$$\textrm{lcm}(\{4,6\})=12$$$. Обратите внимание, что для любого натурального числа $$$x$$$, $$$\gcd(\{x\})=\textrm{lcm}(\{x\})=x$$$.</p><p>У Орака есть последовательность $$$a$$$ длины $$$n$$$. Он придумал мультимножество $$$t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i&lt;j\}$$$ и попросил вас найти $$$\gcd(t)$$$ для него. Иначе говоря, вам нужно найти НОД НОКов всех пар элементов в данной последовательности.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (2\le n\le 100\,000)$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 200\,000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: $$$\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i&lt;j\})$$$.</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 10 24 40 80 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 40 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 540 648 810 648 720 540 594 864 972 648 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 54 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$t=\{\textrm{lcm}(\{1,1\})\}=\{1\}$$$, и $$$\gcd(t)=1$$$.</p><p>Во втором примере $$$t=\{120,40,80,120,240,80\}$$$. Нетрудно видеть, что $$$\gcd(t)=40$$$.</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 11:03: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:'8124a0350ada7b6b',t:'MTY5NjY2NTc4Ny43NjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"]
1350D
1350
D
ru
D. Орак и медианы
<div class="problem-statement"><div class="header"><div class="title">D. Орак и медианы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Слайма есть последовательность натуральных чисел $$$a_1, a_2, \ldots, a_n$$$.</p><p>За одну операцию Орак может выбрать произвольный отрезок $$$[l \ldots r]$$$ этой последовательности и заменить все числа $$$a_l, a_{l + 1}, \ldots, a_r$$$ на значение медианы $$$\{a_l, a_{l + 1}, \ldots, a_r\}$$$.</p><p>В этой задаче для мультимножества натуральных чисел $$$s$$$, медиана $$$s$$$ равна $$$\lfloor \frac{|s|+1}{2}\rfloor$$$-у числу в порядке возрастания в нем. Например, медиана $$$\{1,4,4,6,5\}$$$ равна $$$4$$$, а медиана $$$\{1,7,5,8\}$$$ равна $$$5$$$.</p><p>Слайм хочет, чтобы Орак добился $$$a_1 = a_2 = \ldots = a_n = k$$$ с помощью этих операций.</p><p>Орак думает, что это невозможно, и он не хочет тратить свое время, поэтому он решил спросить вас, можно ли исполнить желание Слайма, и он может задавать вам запросы такого вида несколько раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$: количество запросов.</p><p>В первой строке каждого запроса записано два целых числа $$$n\ (1\le n\le 100\,000)$$$ и $$$k\ (1\le k\le 10^9)$$$, во второй строке записаны $$$n$$$ натуральных чисел $$$a_1,a_2,\dots,a_n\ (1\le a_i\le 10^9)$$$</p><p>Сумма $$$n$$$ по всем запросам не превосходит $$$100\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$t$$$ строк. В $$$i$$$-й из них должно быть записано '<span class="tex-font-style-tt">yes</span>', если возможно превратить все числа в $$$k$$$ за какое-нибудь число операций или '<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 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> no yes yes no yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе Орак не может превратить все элементы в $$$3$$$.</p><p>Во втором запросе $$$a_1=6$$$ уже выполнено.</p><p>В третьем запросе Орак может для операции выбрать весь массив и превратить его в $$$2$$$.</p><p>В четвертом запросе Орак не может превратить все элементы в $$$3$$$.</p><p>В пятом запросе Орак может сначала выбрать $$$[1,6]$$$, а затем $$$[2,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="7457d9db7b547e8379b1aabc20f01d7a"/> <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="2a7eb9afd8de440086ab3af564dd49bf72ea6ae3"/> <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='7457d9db7b547e8379b1aabc20f01d7a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1350%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='7457d9db7b547e8379b1aabc20f01d7a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1350">Codeforces Round 641 (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='7457d9db7b547e8379b1aabc20f01d7a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1350/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='7457d9db7b547e8379b1aabc20f01d7a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619074"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7457d9db7b547e8379b1aabc20f01d7a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619074"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10869" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10878" resourceName="Codeforces Round #641 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/1350">Задачи</a></li> <li><a href="/contest/1350/submit">Отослать</a></li> <li><a href="/contest/1350/my">Мои посылки</a></li> <li><a href="/contest/1350/status">Статус</a></li> <li><a href="/contest/1350/hacks">Взломы</a></li> <li><a href="/contest/1350/room/1">Комната</a></li> <li><a href="/contest/1350/standings">Положение</a></li> <li><a href="/contest/1350/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_fb5729db11f73cdf63657814164f9e2f796913f6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Орак и медианы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Слайма есть последовательность натуральных чисел $$$a_1, a_2, \ldots, a_n$$$.</p><p>За одну операцию Орак может выбрать произвольный отрезок $$$[l \ldots r]$$$ этой последовательности и заменить все числа $$$a_l, a_{l + 1}, \ldots, a_r$$$ на значение медианы $$$\{a_l, a_{l + 1}, \ldots, a_r\}$$$.</p><p>В этой задаче для мультимножества натуральных чисел $$$s$$$, медиана $$$s$$$ равна $$$\lfloor \frac{|s|+1}{2}\rfloor$$$-у числу в порядке возрастания в нем. Например, медиана $$$\{1,4,4,6,5\}$$$ равна $$$4$$$, а медиана $$$\{1,7,5,8\}$$$ равна $$$5$$$.</p><p>Слайм хочет, чтобы Орак добился $$$a_1 = a_2 = \ldots = a_n = k$$$ с помощью этих операций.</p><p>Орак думает, что это невозможно, и он не хочет тратить свое время, поэтому он решил спросить вас, можно ли исполнить желание Слайма, и он может задавать вам запросы такого вида несколько раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$: количество запросов.</p><p>В первой строке каждого запроса записано два целых числа $$$n\ (1\le n\le 100\,000)$$$ и $$$k\ (1\le k\le 10^9)$$$, во второй строке записаны $$$n$$$ натуральных чисел $$$a_1,a_2,\dots,a_n\ (1\le a_i\le 10^9)$$$</p><p>Сумма $$$n$$$ по всем запросам не превосходит $$$100\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$t$$$ строк. В $$$i$$$-й из них должно быть записано '<span class="tex-font-style-tt">yes</span>', если возможно превратить все числа в $$$k$$$ за какое-нибудь число операций или '<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 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> no yes yes no yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе Орак не может превратить все элементы в $$$3$$$.</p><p>Во втором запросе $$$a_1=6$$$ уже выполнено.</p><p>В третьем запросе Орак может для операции выбрать весь массив и превратить его в $$$2$$$.</p><p>В четвертом запросе Орак не может превратить все элементы в $$$3$$$.</p><p>В пятом запросе Орак может сначала выбрать $$$[1,6]$$$, а затем $$$[2,10]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:03: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:'8124a03d3d003a56',t:'MTY5NjY2NTc4OS4wOTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*2000"]
1350E
1350
E
ru
E. Орак и Game of Life
<div class="problem-statement"><div class="header"><div class="title">E. Орак и Game of Life</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>128 мегабайт</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-tt">Game of Life</span>».</p><p>Вы должны играть в эту игру на черно-белом клетчатом поле из $$$n$$$ строк и $$$m$$$ столбцов. Каждая клетка либо белая, либо черная. </p><p>На каждой итерации этой игры (исходная итерация это $$$0$$$) цвет клетки будет изменяться по следующим правилам:</p><ul><li> Если на текущей итерации нет соседних клеток с таким же цветом, как и эта клетка, ее цвет на следующей итерации останется прежним.</li><li> Иначе, ее цвет на следующей итерации будет другим.</li></ul><p>Две клетки являются соседними, если у них есть общая сторона.</p><p>Орак уже выбрал исходное состояние игры, и он хочет знать для клетки $$$(i,j)$$$ (в $$$i$$$-й строке и $$$j$$$-м столбце), чему будет равен ее цвет на итерации $$$p$$$. Он может задавать вам эти вопросы по несколько раз. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано три целых числа $$$n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)$$$, описывающие количество строк и столбцов, и количество запросов Орака.</p><p>Каждая из следующих $$$n$$$ строк содержит бинарную строку длины $$$m$$$, $$$j$$$-й символ в $$$i$$$-й строке описывает изначальный цвет клетки $$$(i,j)$$$. '<span class="tex-font-style-tt">0</span>' означает белый, '<span class="tex-font-style-tt">1</span>' означает черный.</p><p>Каждая из следующих $$$t$$$ строк содержит три целых числа $$$i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})$$$, описывающие запрос Орака.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, в $$$i$$$-й из которых вы должны вывести ответ на $$$i$$$-й запрос Орака. Если цвет клетки черный, вы должны вывести '<span class="tex-font-style-tt">1</span>', иначе, вы должны вывести '<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 3 3 000 111 000 1 1 1 2 2 2 3 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 01 10 01 10 01 1 1 4 5 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 3 01011 10110 01101 11010 10101 1 1 4 1 2 3 5 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 3 0 1 1 1 1 1 2 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/eeb42d9bfc2462ba84fcfac9bf8c45511650f63f.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В первом примере картинка выше описывает исходну ситуацию и цвета клеток на итерациях $$$1$$$, $$$2$$$, и $$$3$$$. Вы можете увидеть, что цвет клетки $$$(1,1)$$$ на итерации $$$1$$$ черный, цвет клетки $$$(2,2)$$$ после итерации $$$2$$$ черный, и цвет клетки $$$(3,3)$$$ после итерации $$$3$$$ тоже черный.</p><p>Во втором примере можно доказать, что клетки никогда не поменяют свой цвет.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b843176b5fc48b255bd55f8d8fc6ba8e"/> <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="2a7eb9afd8de440086ab3af564dd49bf72ea6ae3"/> <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='b843176b5fc48b255bd55f8d8fc6ba8e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1350%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='b843176b5fc48b255bd55f8d8fc6ba8e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1350">Codeforces Round 641 (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='b843176b5fc48b255bd55f8d8fc6ba8e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1350/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='b843176b5fc48b255bd55f8d8fc6ba8e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619075"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b843176b5fc48b255bd55f8d8fc6ba8e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619075"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10869" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10878" resourceName="Codeforces Round #641 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/1350">Задачи</a></li> <li><a href="/contest/1350/submit">Отослать</a></li> <li><a href="/contest/1350/my">Мои посылки</a></li> <li><a href="/contest/1350/status">Статус</a></li> <li><a href="/contest/1350/hacks">Взломы</a></li> <li><a href="/contest/1350/room/1">Комната</a></li> <li><a href="/contest/1350/standings">Положение</a></li> <li><a href="/contest/1350/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5e39910ed16a65eb1acdd86dcde20114ba8dc56b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Орак и Game of Life</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>128 мегабайт</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-tt">Game of Life</span>».</p><p>Вы должны играть в эту игру на черно-белом клетчатом поле из $$$n$$$ строк и $$$m$$$ столбцов. Каждая клетка либо белая, либо черная. </p><p>На каждой итерации этой игры (исходная итерация это $$$0$$$) цвет клетки будет изменяться по следующим правилам:</p><ul><li> Если на текущей итерации нет соседних клеток с таким же цветом, как и эта клетка, ее цвет на следующей итерации останется прежним.</li><li> Иначе, ее цвет на следующей итерации будет другим.</li></ul><p>Две клетки являются соседними, если у них есть общая сторона.</p><p>Орак уже выбрал исходное состояние игры, и он хочет знать для клетки $$$(i,j)$$$ (в $$$i$$$-й строке и $$$j$$$-м столбце), чему будет равен ее цвет на итерации $$$p$$$. Он может задавать вам эти вопросы по несколько раз. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано три целых числа $$$n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)$$$, описывающие количество строк и столбцов, и количество запросов Орака.</p><p>Каждая из следующих $$$n$$$ строк содержит бинарную строку длины $$$m$$$, $$$j$$$-й символ в $$$i$$$-й строке описывает изначальный цвет клетки $$$(i,j)$$$. '<span class="tex-font-style-tt">0</span>' означает белый, '<span class="tex-font-style-tt">1</span>' означает черный.</p><p>Каждая из следующих $$$t$$$ строк содержит три целых числа $$$i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})$$$, описывающие запрос Орака.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, в $$$i$$$-й из которых вы должны вывести ответ на $$$i$$$-й запрос Орака. Если цвет клетки черный, вы должны вывести '<span class="tex-font-style-tt">1</span>', иначе, вы должны вывести '<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 3 3 000 111 000 1 1 1 2 2 2 3 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 01 10 01 10 01 1 1 4 5 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 3 01011 10110 01101 11010 10101 1 1 4 1 2 3 5 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 3 0 1 1 1 1 1 2 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/eeb42d9bfc2462ba84fcfac9bf8c45511650f63f.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В первом примере картинка выше описывает исходну ситуацию и цвета клеток на итерациях $$$1$$$, $$$2$$$, и $$$3$$$. Вы можете увидеть, что цвет клетки $$$(1,1)$$$ на итерации $$$1$$$ черный, цвет клетки $$$(2,2)$$$ после итерации $$$2$$$ черный, и цвет клетки $$$(3,3)$$$ после итерации $$$3$$$ тоже черный.</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 11:03: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:'8124a0459a1f3a55',t:'MTY5NjY2NTc5MC41NTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\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", "*2000"]
1350F
1350
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><span class="tex-font-style-bf">Обратите внимание что единственные различия между версиями это $$$n$$$ и ограничения по времени. Вы можете взламывать, только если обе версии решены.</span></p><p>Слайм интересуется последовательностями. Он определил <span class="tex-font-style-bf">хорошие</span> последовательности $$$p$$$ длины $$$n$$$ из натуральных чисел следующим образом:</p><ul><li> Для каждого $$$k&gt;1$$$, которое встречается в $$$p$$$, должна существовать хотя бы одна пара индексов $$$i,j$$$, такая что $$$1 \leq i &lt; j \leq n$$$, $$$p_i = k - 1$$$ и $$$p_j = k$$$.</li></ul><p>Для данного целого числа $$$n$$$ множество хороших последовательностей длины $$$n$$$ это $$$s_n$$$. Для фиксированного целого числа $$$k$$$ и последовательности $$$p$$$, обозначим за $$$f_p(k)$$$ количество раз, которое $$$k$$$ встречается в $$$p$$$. Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$, Слайм хочет знать следующее значение:</p><p>$$$$$$\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (1\le n\le 5000)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, $$$i$$$-е из них должно быть равно $$$\left(\sum_{p\in s_n} f_p(i)\right)\ \textrm{mod}\ 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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 7 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$s=\{[1,1],[1,2]\}$$$.</p><p>Во втором примере $$$s=\{[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,2],[1,2,3]\}$$$.</p><p>В третьем примере $$$s=\{[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="0b4e9d1a5f584e8957a50e52e69134a9"/> <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="2a7eb9afd8de440086ab3af564dd49bf72ea6ae3"/> <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='0b4e9d1a5f584e8957a50e52e69134a9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1350%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='0b4e9d1a5f584e8957a50e52e69134a9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1350">Codeforces Round 641 (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='0b4e9d1a5f584e8957a50e52e69134a9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1350/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье"> бпф </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='0b4e9d1a5f584e8957a50e52e69134a9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="619077"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0b4e9d1a5f584e8957a50e52e69134a9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="619077"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76895" title="Codeforces Round #641" target="_blank">Codeforces Round #641 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10869" resourceName="Codeforces Round #641" resourceManual="true" src="//codeforces.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/77284" title="Codeforces Round #641 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10878" resourceName="Codeforces Round #641 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/1350">Задачи</a></li> <li><a href="/contest/1350/submit">Отослать</a></li> <li><a href="/contest/1350/my">Мои посылки</a></li> <li><a href="/contest/1350/status">Статус</a></li> <li><a href="/contest/1350/hacks">Взломы</a></li> <li><a href="/contest/1350/room/1">Комната</a></li> <li><a href="/contest/1350/standings">Положение</a></li> <li><a href="/contest/1350/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f51314c4adefee3368abc9a74dca1ea11d384fbb"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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><span class="tex-font-style-bf">Обратите внимание что единственные различия между версиями это $$$n$$$ и ограничения по времени. Вы можете взламывать, только если обе версии решены.</span></p><p>Слайм интересуется последовательностями. Он определил <span class="tex-font-style-bf">хорошие</span> последовательности $$$p$$$ длины $$$n$$$ из натуральных чисел следующим образом:</p><ul><li> Для каждого $$$k&gt;1$$$, которое встречается в $$$p$$$, должна существовать хотя бы одна пара индексов $$$i,j$$$, такая что $$$1 \leq i &lt; j \leq n$$$, $$$p_i = k - 1$$$ и $$$p_j = k$$$.</li></ul><p>Для данного целого числа $$$n$$$ множество хороших последовательностей длины $$$n$$$ это $$$s_n$$$. Для фиксированного целого числа $$$k$$$ и последовательности $$$p$$$, обозначим за $$$f_p(k)$$$ количество раз, которое $$$k$$$ встречается в $$$p$$$. Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$, Слайм хочет знать следующее значение:</p><p>$$$$$$\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n\ (1\le n\le 5000)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, $$$i$$$-е из них должно быть равно $$$\left(\sum_{p\in s_n} f_p(i)\right)\ \textrm{mod}\ 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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 7 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$s=\{[1,1],[1,2]\}$$$.</p><p>Во втором примере $$$s=\{[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,2],[1,2,3]\}$$$.</p><p>В третьем примере $$$s=\{[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 11:03: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:'8124a04eda087b77',t:'MTY5NjY2NTc5Mi4yNDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3100"]
1351A
1351
A
ru
A. A+B (пробная задача)
<div class="problem-statement"><div class="header"><div class="title">A. A+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$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор задан одной строкой, которая содержит два целых числа $$$a$$$, $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел — искомые суммы $$$a+b$$$ для каждого набора входных данных.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 5 314 15 -99 99 123 987 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 329 0 1110 </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="a364f6ffc0e892c9d6a9cb98355c4bab"/> <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="850578c4936ce1b0a1b826dfd1698e0ea2ca6edd"/> <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='a364f6ffc0e892c9d6a9cb98355c4bab'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1351%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='a364f6ffc0e892c9d6a9cb98355c4bab'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1351">Testing Round 16 (Unrated)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a364f6ffc0e892c9d6a9cb98355c4bab'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1351/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='a364f6ffc0e892c9d6a9cb98355c4bab'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="615115"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a364f6ffc0e892c9d6a9cb98355c4bab'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="615115"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76989" title="Testing Round #16 (Unrated)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10858" resourceName="Testing Round #16 (Unrated)" resourceManual="true" src="//codeforces.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/1351">Задачи</a></li> <li><a href="/contest/1351/submit">Отослать</a></li> <li><a href="/contest/1351/my">Мои посылки</a></li> <li><a href="/contest/1351/status">Статус</a></li> <li><a href="/contest/1351/hacks">Взломы</a></li> <li><a href="/contest/1351/room/1">Комната</a></li> <li><a href="/contest/1351/standings">Положение</a></li> <li><a href="/contest/1351/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7f5e8abb477a1b2bbe385f7d4100e3bff4faf092"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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+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$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор задан одной строкой, которая содержит два целых числа $$$a$$$, $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел — искомые суммы $$$a+b$$$ для каждого набора входных данных.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 5 314 15 -99 99 123 987 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 329 0 1110 </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 11:03: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:'8124a0592e141654',t:'MTY5NjY2NTc5My42MDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1351B
1351
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></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор задан двумя строками.</p><p>Первая строка содержит два целых числа $$$a_1$$$ и $$$b_1$$$ ($$$1 \le a_1, b_1 \le 100$$$) — размеры первого из полученных после разрезания прямоугольника. Размеры заданы в произвольном порядке (то есть неизвестно какое из чисел является шириной, а какое из чисел — длинной).</p><p>Вторая строка содержит два целых числа $$$a_2$$$ и $$$b_2$$$ ($$$1 \le a_2, b_2 \le 100$$$) — размеры второго из полученных после разрезания прямоугольника. Размеры заданы в произвольном порядке (то есть неизвестно какое из чисел является шириной, а какое из чисел — длинной).</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 2 3 3 1 3 2 1 3 3 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes No </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="256af81d3df1984f9ba7a06542dcad17"/> <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="850578c4936ce1b0a1b826dfd1698e0ea2ca6edd"/> <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='256af81d3df1984f9ba7a06542dcad17'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1351%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='256af81d3df1984f9ba7a06542dcad17'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1351">Testing Round 16 (Unrated)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='256af81d3df1984f9ba7a06542dcad17'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1351/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='256af81d3df1984f9ba7a06542dcad17'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="615116"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='256af81d3df1984f9ba7a06542dcad17'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="615116"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76989" title="Testing Round #16 (Unrated)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10858" resourceName="Testing Round #16 (Unrated)" resourceManual="true" src="//codeforces.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/1351">Задачи</a></li> <li><a href="/contest/1351/submit">Отослать</a></li> <li><a href="/contest/1351/my">Мои посылки</a></li> <li><a href="/contest/1351/status">Статус</a></li> <li><a href="/contest/1351/hacks">Взломы</a></li> <li><a href="/contest/1351/room/1">Комната</a></li> <li><a href="/contest/1351/standings">Положение</a></li> <li><a href="/contest/1351/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5e17d3ff8c328f41d5985b572561898574ac1bd3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор задан двумя строками.</p><p>Первая строка содержит два целых числа $$$a_1$$$ и $$$b_1$$$ ($$$1 \le a_1, b_1 \le 100$$$) — размеры первого из полученных после разрезания прямоугольника. Размеры заданы в произвольном порядке (то есть неизвестно какое из чисел является шириной, а какое из чисел — длинной).</p><p>Вторая строка содержит два целых числа $$$a_2$$$ и $$$b_2$$$ ($$$1 \le a_2, b_2 \le 100$$$) — размеры второго из полученных после разрезания прямоугольника. Размеры заданы в произвольном порядке (то есть неизвестно какое из чисел является шириной, а какое из чисел — длинной).</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 2 3 3 1 3 2 1 3 3 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes Yes No </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 11:03: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:'8124a061adda16cb',t:'MTY5NjY2NTc5NC45NTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*900"]
1351C
1351
C
ru
C. Лыжник
<div class="problem-statement"><div class="header"><div class="title">C. Лыжник</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Лыжник катается по снежному полю. Его передвижения можно описать строкой из символов '<span class="tex-font-style-tt">S</span>', '<span class="tex-font-style-tt">N</span>', '<span class="tex-font-style-tt">W</span>', '<span class="tex-font-style-tt">E</span>' (что соответствует перемещениям на $$$1$$$ метр в направлении юга, севера, запада или востока соответственно).</p><p>Известно, что если он прокладывает лыжню (то есть катится по ранее не посещенному отрезку пути), то время такого передвижения равно $$$5$$$ секунд, а если он катится по лыжне, то $$$1$$$ секунду.</p><p>Найдите время лыжника в пути.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор задан одной непустой строкой из символов '<span class="tex-font-style-tt">S</span>', '<span class="tex-font-style-tt">N</span>', '<span class="tex-font-style-tt">W</span>', '<span class="tex-font-style-tt">E</span>'. Длина строки не превосходит $$$10^5$$$ символов.</p><p>Сумма длин $$$t$$$ строк по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите искомое время прохождения пути в секундах.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 NNN NS WWEN WWEE NWNWS </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 6 16 12 25 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a453aebe060f06ff2943495a33e17dd7"/> <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="850578c4936ce1b0a1b826dfd1698e0ea2ca6edd"/> <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='a453aebe060f06ff2943495a33e17dd7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1351%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='a453aebe060f06ff2943495a33e17dd7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1351">Testing Round 16 (Unrated)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a453aebe060f06ff2943495a33e17dd7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1351/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='a453aebe060f06ff2943495a33e17dd7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="615117"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a453aebe060f06ff2943495a33e17dd7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="615117"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/76989" title="Testing Round #16 (Unrated)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10858" resourceName="Testing Round #16 (Unrated)" resourceManual="true" src="//codeforces.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/1351">Задачи</a></li> <li><a href="/contest/1351/submit">Отослать</a></li> <li><a href="/contest/1351/my">Мои посылки</a></li> <li><a href="/contest/1351/status">Статус</a></li> <li><a href="/contest/1351/hacks">Взломы</a></li> <li><a href="/contest/1351/room/1">Комната</a></li> <li><a href="/contest/1351/standings">Положение</a></li> <li><a href="/contest/1351/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d372afe13d077b6c064136b0752aa0113977a428"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Лыжник</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Лыжник катается по снежному полю. Его передвижения можно описать строкой из символов '<span class="tex-font-style-tt">S</span>', '<span class="tex-font-style-tt">N</span>', '<span class="tex-font-style-tt">W</span>', '<span class="tex-font-style-tt">E</span>' (что соответствует перемещениям на $$$1$$$ метр в направлении юга, севера, запада или востока соответственно).</p><p>Известно, что если он прокладывает лыжню (то есть катится по ранее не посещенному отрезку пути), то время такого передвижения равно $$$5$$$ секунд, а если он катится по лыжне, то $$$1$$$ секунду.</p><p>Найдите время лыжника в пути.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор задан одной непустой строкой из символов '<span class="tex-font-style-tt">S</span>', '<span class="tex-font-style-tt">N</span>', '<span class="tex-font-style-tt">W</span>', '<span class="tex-font-style-tt">E</span>'. Длина строки не превосходит $$$10^5$$$ символов.</p><p>Сумма длин $$$t$$$ строк по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите искомое время прохождения пути в секундах.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 NNN NS WWEN WWEE NWNWS </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 6 16 12 25 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:03: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:'8124a06a1db69d9f',t:'MTY5NjY2NTc5Ni4yOTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1352A
1352
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>, если оно имеет вид <span class="tex-font-style-tt">d00...0</span>. Иными словами, положительное целое число является круглым, если все его цифры, кроме самой левой (старшей), равны нулю. В частности, все числа от $$$1$$$ до $$$9$$$ (включительно) являются круглыми.</p><p>Например, следующие числа являются круглыми: $$$4000$$$, $$$1$$$, $$$9$$$, $$$800$$$, $$$90$$$. Например, следующие числа <span class="tex-font-style-bf">не</span> являются круглыми: $$$110$$$, $$$707$$$, $$$222$$$, $$$1001$$$.</p><p>Вам задано целое положительное число $$$n$$$ ($$$1 \le n \le 10^4$$$). Представьте число $$$n$$$ как сумму круглых чисел, используя минимальное количество слагаемых. Иными словами, вам надо разложить заданное число $$$n$$$ в сумму наименьшего количества слагаемых, каждое из которых является круглым числом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор представляет собой строку, в которой записано целое число $$$n$$$ ($$$1 \le n \le 10^4$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных. Каждый ответ должен начинаться с целого числа $$$k$$$ — минимального количества слагаемых. Далее должны следовать $$$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 5009 7 9876 10000 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 5000 9 1 7 4 800 70 6 9000 1 10000 1 10 </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="65fd7520bfc4118a430a7f036d780ad9"/> <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="a93983fc9e9a8c248f6350731e5df450cf7f9733"/> <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='65fd7520bfc4118a430a7f036d780ad9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1352%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='65fd7520bfc4118a430a7f036d780ad9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1352">Codeforces Round 640 (Div. 4)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='65fd7520bfc4118a430a7f036d780ad9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1352/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='65fd7520bfc4118a430a7f036d780ad9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="616893"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='65fd7520bfc4118a430a7f036d780ad9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="616893"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77130" title="77130" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15627" resourceName="77130" resourceManual="true" src="//codeforces.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/77161" title="77161" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15628" resourceName="77161" resourceManual="true" src="//codeforces.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/1352">Задачи</a></li> <li><a href="/contest/1352/submit">Отослать</a></li> <li><a href="/contest/1352/my">Мои посылки</a></li> <li><a href="/contest/1352/status">Статус</a></li> <li><a href="/contest/1352/hacks">Взломы</a></li> <li><a href="/contest/1352/standings">Положение</a></li> <li><a href="/contest/1352/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d1dea6f02c439b1bd8815ca7c4c2aac08c90ac25"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>, если оно имеет вид <span class="tex-font-style-tt">d00...0</span>. Иными словами, положительное целое число является круглым, если все его цифры, кроме самой левой (старшей), равны нулю. В частности, все числа от $$$1$$$ до $$$9$$$ (включительно) являются круглыми.</p><p>Например, следующие числа являются круглыми: $$$4000$$$, $$$1$$$, $$$9$$$, $$$800$$$, $$$90$$$. Например, следующие числа <span class="tex-font-style-bf">не</span> являются круглыми: $$$110$$$, $$$707$$$, $$$222$$$, $$$1001$$$.</p><p>Вам задано целое положительное число $$$n$$$ ($$$1 \le n \le 10^4$$$). Представьте число $$$n$$$ как сумму круглых чисел, используя минимальное количество слагаемых. Иными словами, вам надо разложить заданное число $$$n$$$ в сумму наименьшего количества слагаемых, каждое из которых является круглым числом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор представляет собой строку, в которой записано целое число $$$n$$$ ($$$1 \le n \le 10^4$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных. Каждый ответ должен начинаться с целого числа $$$k$$$ — минимального количества слагаемых. Далее должны следовать $$$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 5009 7 9876 10000 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 5000 9 1 7 4 800 70 6 9000 1 10000 1 10 </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 11:03: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:'8124a0728ab616c7',t:'MTY5NjY2NTc5Ny42MzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"]
1352B
1352
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 \le n \le 10^9$$$) и $$$k$$$ ($$$1 \le k \le 100$$$). Представьте число $$$n$$$ в виде суммы $$$k$$$ положительных целых чисел одинаковой четности (с одинаковыми остатками от деления на $$$2$$$). </p><p>Иными словами, найдите такие $$$a_1, a_2, \ldots, a_k$$$, что все $$$a_i&gt;0$$$, $$$n = a_1 + a_2 + \ldots + a_k$$$ и либо все $$$a_i$$$ одновременно четные, либо все $$$a_i$$$ одновременно нечетные. Если такого представления не существует, то сообщите об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее записаны $$$t$$$ наборов входных данных по одному в строке.</p><p>Каждый набор представляет собой два целых положительных числа $$$n$$$ ($$$1 \le n \le 10^9$$$) и $$$k$$$ ($$$1 \le k \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите:</p><ul> <li> <span class="tex-font-style-tt">YES</span> и искомые $$$a_i$$$, если ответ существует (если ответов несколько, то выведите любой из них); </li><li> <span class="tex-font-style-tt">NO</span>, если ответа не существует. </li></ul><p>Буквы в словах <span class="tex-font-style-tt">YES</span> и <span class="tex-font-style-tt">NO</span> можно выводить в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 10 3 100 4 8 7 97 2 8 8 3 10 5 3 1000000000 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 4 2 4 YES 55 5 5 35 NO NO YES 1 1 1 1 1 1 1 1 NO YES 3 1 1 YES 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120 </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="d1637574e6c5bb97679424a571836586"/> <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="a93983fc9e9a8c248f6350731e5df450cf7f9733"/> <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='d1637574e6c5bb97679424a571836586'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1352%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='d1637574e6c5bb97679424a571836586'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1352">Codeforces Round 640 (Div. 4)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='d1637574e6c5bb97679424a571836586'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1352/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='d1637574e6c5bb97679424a571836586'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="616894"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d1637574e6c5bb97679424a571836586'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="616894"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77130" title="77130" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15627" resourceName="77130" resourceManual="true" src="//codeforces.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/77161" title="77161" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15628" resourceName="77161" resourceManual="true" src="//codeforces.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/1352">Задачи</a></li> <li><a href="/contest/1352/submit">Отослать</a></li> <li><a href="/contest/1352/my">Мои посылки</a></li> <li><a href="/contest/1352/status">Статус</a></li> <li><a href="/contest/1352/hacks">Взломы</a></li> <li><a href="/contest/1352/standings">Положение</a></li> <li><a href="/contest/1352/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6507fa10d0d7c51835f76f0d5cee0e7f17a4fe91"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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 \le n \le 10^9$$$) и $$$k$$$ ($$$1 \le k \le 100$$$). Представьте число $$$n$$$ в виде суммы $$$k$$$ положительных целых чисел одинаковой четности (с одинаковыми остатками от деления на $$$2$$$). </p><p>Иными словами, найдите такие $$$a_1, a_2, \ldots, a_k$$$, что все $$$a_i&gt;0$$$, $$$n = a_1 + a_2 + \ldots + a_k$$$ и либо все $$$a_i$$$ одновременно четные, либо все $$$a_i$$$ одновременно нечетные. Если такого представления не существует, то сообщите об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее записаны $$$t$$$ наборов входных данных по одному в строке.</p><p>Каждый набор представляет собой два целых положительных числа $$$n$$$ ($$$1 \le n \le 10^9$$$) и $$$k$$$ ($$$1 \le k \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите:</p><ul> <li> <span class="tex-font-style-tt">YES</span> и искомые $$$a_i$$$, если ответ существует (если ответов несколько, то выведите любой из них); </li><li> <span class="tex-font-style-tt">NO</span>, если ответа не существует. </li></ul><p>Буквы в словах <span class="tex-font-style-tt">YES</span> и <span class="tex-font-style-tt">NO</span> можно выводить в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 10 3 100 4 8 7 97 2 8 8 3 10 5 3 1000000000 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 4 2 4 YES 55 5 5 35 NO NO YES 1 1 1 1 1 1 1 1 NO YES 3 1 1 YES 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120 </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 11:03: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:'8124a07afdb09d8c',t:'MTY5NjY2NTc5OC45NzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1200"]
1352C
1352
C
ru
C. K-е неделящееся на n
<div class="problem-statement"><div class="header"><div class="title">C. K-е неделящееся на n</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Заданы два целых положительных числа: $$$n$$$ и $$$k$$$. Выведите $$$k$$$-е положительное целое число, которое не делится на $$$n$$$.</p><p>Например, если $$$n=3$$$, а $$$k=7$$$, то все числа, которые не делятся на $$$3$$$, имеют вид: $$$1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$$$. $$$7$$$-е число среди них равно $$$10$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее записаны $$$t$$$ наборов входных данных по одному в строке.</p><p>Каждый набор представляет собой два целых положительных числа $$$n$$$ ($$$2 \le n \le 10^9$$$) и $$$k$$$ ($$$1 \le k \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$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> 6 3 7 4 12 2 1000000000 7 97 1000000000 1000000000 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 15 1999999999 113 1000000001 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="6c18d8163f1266b5d827eb0a6bbd56f2"/> <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="a93983fc9e9a8c248f6350731e5df450cf7f9733"/> <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='6c18d8163f1266b5d827eb0a6bbd56f2'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1352%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='6c18d8163f1266b5d827eb0a6bbd56f2'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1352">Codeforces Round 640 (Div. 4)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='6c18d8163f1266b5d827eb0a6bbd56f2'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1352/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='6c18d8163f1266b5d827eb0a6bbd56f2'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="616895"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6c18d8163f1266b5d827eb0a6bbd56f2'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="616895"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77130" title="77130" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15627" resourceName="77130" resourceManual="true" src="//codeforces.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/77161" title="77161" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15628" resourceName="77161" resourceManual="true" src="//codeforces.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/1352">Задачи</a></li> <li><a href="/contest/1352/submit">Отослать</a></li> <li><a href="/contest/1352/my">Мои посылки</a></li> <li><a href="/contest/1352/status">Статус</a></li> <li><a href="/contest/1352/hacks">Взломы</a></li> <li><a href="/contest/1352/standings">Положение</a></li> <li><a href="/contest/1352/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6a8912c95554514a91d8c811a6c48dd2a957ae87"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. K-е неделящееся на n</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Заданы два целых положительных числа: $$$n$$$ и $$$k$$$. Выведите $$$k$$$-е положительное целое число, которое не делится на $$$n$$$.</p><p>Например, если $$$n=3$$$, а $$$k=7$$$, то все числа, которые не делятся на $$$3$$$, имеют вид: $$$1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$$$. $$$7$$$-е число среди них равно $$$10$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее записаны $$$t$$$ наборов входных данных по одному в строке.</p><p>Каждый набор представляет собой два целых положительных числа $$$n$$$ ($$$2 \le n \le 10^9$$$) и $$$k$$$ ($$$1 \le k \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$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> 6 3 7 4 12 2 1000000000 7 97 1000000000 1000000000 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 15 1999999999 113 1000000001 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 11:03: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:'8124a08369fd7b53',t:'MTY5NjY2NTgwMC4yOTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1200"]
1352D
1352
D
ru
D. Алиса, Боб и конфеты
<div class="problem-statement"><div class="header"><div class="title">D. Алиса, Боб и конфеты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В ряд выложены $$$n$$$ конфет, которые пронумерованы слева направо от $$$1$$$ до $$$n$$$. Размер $$$i$$$-й конфеты равен $$$a_i$$$.</p><p>Алиса и Боб играют в интересную и вкусную игру — они едят конфеты. Алиса будет есть конфеты <span class="tex-font-style-bf">слева направо</span>, а Боб — <span class="tex-font-style-bf">справа налево</span>. Игра заканчивается, когда все конфеты съедены.</p><p>Процесс состоит из ходов. Во время хода игрок съедает одну или более конфет со своей стороны (Алиса ест слева, Боб — справа). Первый ход делает Алиса. Во время первого хода она съест $$$1$$$ конфету (ее размер равен $$$a_1$$$). Затем каждый следующий ход стороны чередуются — то есть второй ход совершает Боб, затем Алиса, затем снова Боб и так далее.</p><p>На каждом ходу игрок считает суммарный размер конфет, съеденных за текущий ход. Как только это число становится строго больше, чем суммарный размер конфет, съеденных другим игроком на предыдущем ходу, текущий игрок завершает ход. Иными словами, на очередном ходу игрок ест наименьшее возможное количество конфет, при котором сумма размеров съеденных в этот ход конфет <span class="tex-font-style-bf">строго больше</span> суммы размеров конфет, которые съел другой игрок на <span class="tex-font-style-bf">предыдущем</span> ходу. Если конфет недостаточно, чтобы совершить ход таким образом, то игрок доедает все оставшиеся конфеты и игра заканчивается.</p><p>Например, если $$$n=11$$$ и $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, то:</p><ul> <li> ход 1: Алиса съест одну конфету размера $$$3$$$ и последовательность конфет примет вид $$$[1,4,1,5,9,2,6,5,3,5]$$$; </li><li> ход 2: на предыдущем ходу Алиса съела $$$3$$$, значит, Боб должен съесть $$$4$$$ или более — Боб съест одну конфету размера $$$5$$$ и последовательность конфет примет вид $$$[1,4,1,5,9,2,6,5,3]$$$; </li><li> ход 3: на предыдущем ходу Боб съел $$$5$$$, значит, Алиса должна съесть $$$6$$$ или более — Алиса съест три конфеты суммарным размером $$$1+4+1=6$$$ и последовательность конфет примет вид $$$[5,9,2,6,5,3]$$$; </li><li> ход 4: на предыдущем ходу Алиса съела $$$6$$$, значит, Боб должен съесть $$$7$$$ или более — Боб съест две конфеты суммарным размером $$$3+5=8$$$ и последовательность конфет примет вид $$$[5,9,2,6]$$$; </li><li> ход 5: на предыдущем ходу Боб съел $$$8$$$, значит, Алиса должна съесть $$$9$$$ или более — на пятом ходу Алиса съест две конфеты суммарным размером $$$5+9=14$$$ и последовательность конфет примет вид $$$[2,6]$$$; </li><li> ход 6 (последний): на предыдущем ходу Алиса съела $$$14$$$, значит, Боб должен съесть $$$15$$$ или более — это невозможно, поэтому Боб съест две оставшиеся конфеты и игра закончится. </li></ul><p>Выведите количество ходов в этой игре и два числа:</p><ul> <li> $$$a$$$ — суммарный размер всех конфет, съеденных Алисой за всю игру; </li><li> $$$b$$$ — суммарный размер всех конфет, съеденных Бобом за всю игру. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 5000$$$) — количество наборов входных данных. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Каждый набор состоит из двух строк. В первой строке содержится целое число $$$n$$$ ($$$1 \le n \le 1000$$$) — количество конфет. Во второй строке содержится последовательность целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — размеры конфет в порядке их расположения слева направо.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$2\cdot10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите три целых числа — количество ходов в игре и искомые величины $$$a$$$ и $$$b$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 11 3 1 4 1 5 9 2 6 5 3 5 1 1000 3 1 1 1 13 1 2 3 4 5 6 7 8 9 10 11 12 13 2 2 1 6 1 1 1 1 1 1 7 1 1 1 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 23 21 1 1000 0 2 1 2 6 45 46 2 2 1 3 4 2 4 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="111f274e70d1bbce78cf3304671691aa"/> <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="a93983fc9e9a8c248f6350731e5df450cf7f9733"/> <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='111f274e70d1bbce78cf3304671691aa'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1352%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='111f274e70d1bbce78cf3304671691aa'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1352">Codeforces Round 640 (Div. 4)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='111f274e70d1bbce78cf3304671691aa'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1352/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='111f274e70d1bbce78cf3304671691aa'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="616896"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='111f274e70d1bbce78cf3304671691aa'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="616896"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77130" title="77130" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15627" resourceName="77130" resourceManual="true" src="//codeforces.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/77161" title="77161" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15628" resourceName="77161" resourceManual="true" src="//codeforces.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/1352">Задачи</a></li> <li><a href="/contest/1352/submit">Отослать</a></li> <li><a href="/contest/1352/my">Мои посылки</a></li> <li><a href="/contest/1352/status">Статус</a></li> <li><a href="/contest/1352/hacks">Взломы</a></li> <li><a href="/contest/1352/standings">Положение</a></li> <li><a href="/contest/1352/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9511a5ade9387a9f885669fab4414357ae1d7b10"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Алиса, Боб и конфеты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В ряд выложены $$$n$$$ конфет, которые пронумерованы слева направо от $$$1$$$ до $$$n$$$. Размер $$$i$$$-й конфеты равен $$$a_i$$$.</p><p>Алиса и Боб играют в интересную и вкусную игру — они едят конфеты. Алиса будет есть конфеты <span class="tex-font-style-bf">слева направо</span>, а Боб — <span class="tex-font-style-bf">справа налево</span>. Игра заканчивается, когда все конфеты съедены.</p><p>Процесс состоит из ходов. Во время хода игрок съедает одну или более конфет со своей стороны (Алиса ест слева, Боб — справа). Первый ход делает Алиса. Во время первого хода она съест $$$1$$$ конфету (ее размер равен $$$a_1$$$). Затем каждый следующий ход стороны чередуются — то есть второй ход совершает Боб, затем Алиса, затем снова Боб и так далее.</p><p>На каждом ходу игрок считает суммарный размер конфет, съеденных за текущий ход. Как только это число становится строго больше, чем суммарный размер конфет, съеденных другим игроком на предыдущем ходу, текущий игрок завершает ход. Иными словами, на очередном ходу игрок ест наименьшее возможное количество конфет, при котором сумма размеров съеденных в этот ход конфет <span class="tex-font-style-bf">строго больше</span> суммы размеров конфет, которые съел другой игрок на <span class="tex-font-style-bf">предыдущем</span> ходу. Если конфет недостаточно, чтобы совершить ход таким образом, то игрок доедает все оставшиеся конфеты и игра заканчивается.</p><p>Например, если $$$n=11$$$ и $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, то:</p><ul> <li> ход 1: Алиса съест одну конфету размера $$$3$$$ и последовательность конфет примет вид $$$[1,4,1,5,9,2,6,5,3,5]$$$; </li><li> ход 2: на предыдущем ходу Алиса съела $$$3$$$, значит, Боб должен съесть $$$4$$$ или более — Боб съест одну конфету размера $$$5$$$ и последовательность конфет примет вид $$$[1,4,1,5,9,2,6,5,3]$$$; </li><li> ход 3: на предыдущем ходу Боб съел $$$5$$$, значит, Алиса должна съесть $$$6$$$ или более — Алиса съест три конфеты суммарным размером $$$1+4+1=6$$$ и последовательность конфет примет вид $$$[5,9,2,6,5,3]$$$; </li><li> ход 4: на предыдущем ходу Алиса съела $$$6$$$, значит, Боб должен съесть $$$7$$$ или более — Боб съест две конфеты суммарным размером $$$3+5=8$$$ и последовательность конфет примет вид $$$[5,9,2,6]$$$; </li><li> ход 5: на предыдущем ходу Боб съел $$$8$$$, значит, Алиса должна съесть $$$9$$$ или более — на пятом ходу Алиса съест две конфеты суммарным размером $$$5+9=14$$$ и последовательность конфет примет вид $$$[2,6]$$$; </li><li> ход 6 (последний): на предыдущем ходу Алиса съела $$$14$$$, значит, Боб должен съесть $$$15$$$ или более — это невозможно, поэтому Боб съест две оставшиеся конфеты и игра закончится. </li></ul><p>Выведите количество ходов в этой игре и два числа:</p><ul> <li> $$$a$$$ — суммарный размер всех конфет, съеденных Алисой за всю игру; </li><li> $$$b$$$ — суммарный размер всех конфет, съеденных Бобом за всю игру. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 5000$$$) — количество наборов входных данных. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Каждый набор состоит из двух строк. В первой строке содержится целое число $$$n$$$ ($$$1 \le n \le 1000$$$) — количество конфет. Во второй строке содержится последовательность целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — размеры конфет в порядке их расположения слева направо.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$2\cdot10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите три целых числа — количество ходов в игре и искомые величины $$$a$$$ и $$$b$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 11 3 1 4 1 5 9 2 6 5 3 5 1 1000 3 1 1 1 13 1 2 3 4 5 6 7 8 9 10 11 12 13 2 2 1 6 1 1 1 1 1 1 7 1 1 1 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 23 21 1 1000 0 2 1 2 6 45 46 2 2 1 3 4 2 4 4 3 </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 11:03: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:'8124a08b883513ba',t:'MTY5NjY2NTgwMS41NzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1300"]
1352E
1352
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>64 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Обратите внимание на нестандартное ограничение по памяти в этой задаче.</span></p><p><span class="tex-font-style-it">С целью отсечения эффективных решений от неэффективных в этой задаче ограничение времени довольно строгое. Предпочтите использование компилируемых статически типизированных языков (например, C++). Если используете Python, то отсылайте решения на PyPy. Постарайтесь написать в самом деле эффективное решение.</span></p><p>Задан массив $$$a=[a_1, a_2, \ldots, a_n]$$$ ($$$1 \le a_i \le n$$$). Его элемент $$$a_i$$$ называется особым, если существует такая пара индексов $$$l$$$ и $$$r$$$ ($$$1 \le l &lt; r \le n$$$), что $$$a_i = a_l + a_{l+1} + \ldots + a_r$$$. Иными словами, элемент называется особым, если он представим в виде суммы <span class="tex-font-style-bf">двух или более подряд идущих элементов</span> массива (не важно, особых или нет).</p><p>Выведите количество особых элементов заданного массива $$$a$$$.</p><p>Например, если $$$n=9$$$ и $$$a=[3,1,4,1,5,9,2,6,5]$$$, то ответ равен $$$5$$$:</p><ul> <li> $$$a_3=4$$$ — особый элемент, так как $$$a_3=4=a_1+a_2=3+1$$$; </li><li> $$$a_5=5$$$ — особый элемент, так как $$$a_5=5=a_2+a_3=1+4$$$; </li><li> $$$a_6=9$$$ — особый элемент, так как $$$a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$$$; </li><li> $$$a_8=6$$$ — особый элемент, так как $$$a_8=6=a_2+a_3+a_4=1+4+1$$$; </li><li> $$$a_9=5$$$ — особый элемент, так как $$$a_9=5=a_2+a_3=1+4$$$. </li></ul><p>Обратите внимание, что среди элементов массива $$$a$$$ могут быть равные — если несколько элементов равны и являются особыми, то все они должны быть посчитаны в ответе.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Каждый набор задается двумя строками. В первой строке записано целое число $$$n$$$ ($$$1 \le n \le 8000$$$) — длина массива $$$a$$$. Во второй строке записаны целые числа $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$).</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$8000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ чисел — количества особых элементов для каждого из заданных массивов.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 9 3 1 4 1 5 9 2 6 5 3 1 1 2 5 1 1 1 1 1 8 8 7 6 5 4 3 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 0 4 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="27a1d88cc7274dd99aa0524f9d7346ea"/> <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="a93983fc9e9a8c248f6350731e5df450cf7f9733"/> <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='27a1d88cc7274dd99aa0524f9d7346ea'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1352%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='27a1d88cc7274dd99aa0524f9d7346ea'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1352">Codeforces Round 640 (Div. 4)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='27a1d88cc7274dd99aa0524f9d7346ea'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1352/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='27a1d88cc7274dd99aa0524f9d7346ea'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="616897"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='27a1d88cc7274dd99aa0524f9d7346ea'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="616897"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77130" title="77130" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15627" resourceName="77130" resourceManual="true" src="//codeforces.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/77161" title="77161" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15628" resourceName="77161" resourceManual="true" src="//codeforces.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/1352">Задачи</a></li> <li><a href="/contest/1352/submit">Отослать</a></li> <li><a href="/contest/1352/my">Мои посылки</a></li> <li><a href="/contest/1352/status">Статус</a></li> <li><a href="/contest/1352/hacks">Взломы</a></li> <li><a href="/contest/1352/standings">Положение</a></li> <li><a href="/contest/1352/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_944ed03ede769898e04672528d79403fe61be071"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>64 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Обратите внимание на нестандартное ограничение по памяти в этой задаче.</span></p><p><span class="tex-font-style-it">С целью отсечения эффективных решений от неэффективных в этой задаче ограничение времени довольно строгое. Предпочтите использование компилируемых статически типизированных языков (например, C++). Если используете Python, то отсылайте решения на PyPy. Постарайтесь написать в самом деле эффективное решение.</span></p><p>Задан массив $$$a=[a_1, a_2, \ldots, a_n]$$$ ($$$1 \le a_i \le n$$$). Его элемент $$$a_i$$$ называется особым, если существует такая пара индексов $$$l$$$ и $$$r$$$ ($$$1 \le l &lt; r \le n$$$), что $$$a_i = a_l + a_{l+1} + \ldots + a_r$$$. Иными словами, элемент называется особым, если он представим в виде суммы <span class="tex-font-style-bf">двух или более подряд идущих элементов</span> массива (не важно, особых или нет).</p><p>Выведите количество особых элементов заданного массива $$$a$$$.</p><p>Например, если $$$n=9$$$ и $$$a=[3,1,4,1,5,9,2,6,5]$$$, то ответ равен $$$5$$$:</p><ul> <li> $$$a_3=4$$$ — особый элемент, так как $$$a_3=4=a_1+a_2=3+1$$$; </li><li> $$$a_5=5$$$ — особый элемент, так как $$$a_5=5=a_2+a_3=1+4$$$; </li><li> $$$a_6=9$$$ — особый элемент, так как $$$a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$$$; </li><li> $$$a_8=6$$$ — особый элемент, так как $$$a_8=6=a_2+a_3+a_4=1+4+1$$$; </li><li> $$$a_9=5$$$ — особый элемент, так как $$$a_9=5=a_2+a_3=1+4$$$. </li></ul><p>Обратите внимание, что среди элементов массива $$$a$$$ могут быть равные — если несколько элементов равны и являются особыми, то все они должны быть посчитаны в ответе.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Каждый набор задается двумя строками. В первой строке записано целое число $$$n$$$ ($$$1 \le n \le 8000$$$) — длина массива $$$a$$$. Во второй строке записаны целые числа $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$).</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$8000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ чисел — количества особых элементов для каждого из заданных массивов.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 9 3 1 4 1 5 9 2 6 5 3 1 1 2 5 1 1 1 1 1 8 8 7 6 5 4 3 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 0 4 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:03: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:'8124a0938a3d9db4',t:'MTY5NjY2NTgwMi44NTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1500"]
1352F
1352
F
ru
F. Восстановление 01-строки
<div class="problem-statement"><div class="header"><div class="title">F. Восстановление 01-строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для некоторой 01-строки $$$s$$$ (то есть такой, что каждый символ $$$s_i$$$ — это либо '<span class="tex-font-style-tt">0</span>', либо '<span class="tex-font-style-tt">1</span>') выписали все пары подряд идущих символов (все подстроки длины $$$2$$$). Для каждой пары (подстроки длины $$$2$$$) посчитали количество символов '<span class="tex-font-style-tt">1</span>' (единиц) в ней.</p><p>Вам заданы три числа:</p><ul> <li> $$$n_0$$$ — количество пар подряд идущих символов (подстрок), в которых $$$0$$$ единиц; </li><li> $$$n_1$$$ — количество пар подряд идущих символов (подстрок), в которых $$$1$$$ единица; </li><li> $$$n_2$$$ — количество пар подряд идущих символов (подстрок), в которых $$$2$$$ единицы. </li></ul><p>Например, для строки $$$s=$$$«<span class="tex-font-style-tt">1110011110</span>» были бы выписаны следующие подстроки: «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">10</span>», «<span class="tex-font-style-tt">00</span>», «<span class="tex-font-style-tt">01</span>», «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">10</span>». Таким образом, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.</p><p>Ваша задача — по заданным $$$n_0, n_1, n_2$$$ восстановить <span class="tex-font-style-bf">любую</span> подходящую 01-строку (бинарную строку) $$$s$$$. Гарантируется, что хотя бы одно из чисел $$$n_0, n_1, n_2$$$ отлично от $$$0$$$. Также гарантируется, что решение существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее во входных данных записаны сами наборы.</p><p>Каждый набор состоит из одной строки, которая содержит три целых числа $$$n_0, n_1, n_2$$$ ($$$0 \le n_0, n_1, n_2 \le 100$$$; $$$n_0 + n_1 + n_2 &gt; 0$$$). Гарантируется, что ответ для заданных $$$n_0, n_1, n_2$$$ существует.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Каждая из строк должна содержать ответ в виде 01-строки (бинарной строки) на соответствующий набор входных данных. Если возможных ответов несколько, выведите любой из них.</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 3 5 1 1 1 3 9 3 0 1 0 3 1 2 0 0 3 2 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1110011110 0011 0110001100101011 10 0000111 1111 000 </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="c853e5efded0d25519d1f0e36e29f872"/> <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="a93983fc9e9a8c248f6350731e5df450cf7f9733"/> <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='c853e5efded0d25519d1f0e36e29f872'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1352%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='c853e5efded0d25519d1f0e36e29f872'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1352">Codeforces Round 640 (Div. 4)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='c853e5efded0d25519d1f0e36e29f872'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1352/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='c853e5efded0d25519d1f0e36e29f872'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="616898"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c853e5efded0d25519d1f0e36e29f872'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="616898"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77130" title="77130" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15627" resourceName="77130" resourceManual="true" src="//codeforces.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/77161" title="77161" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15628" resourceName="77161" resourceManual="true" src="//codeforces.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/1352">Задачи</a></li> <li><a href="/contest/1352/submit">Отослать</a></li> <li><a href="/contest/1352/my">Мои посылки</a></li> <li><a href="/contest/1352/status">Статус</a></li> <li><a href="/contest/1352/hacks">Взломы</a></li> <li><a href="/contest/1352/standings">Положение</a></li> <li><a href="/contest/1352/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_68479be38e654791db98929f2022dc6f08f07e6d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Восстановление 01-строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для некоторой 01-строки $$$s$$$ (то есть такой, что каждый символ $$$s_i$$$ — это либо '<span class="tex-font-style-tt">0</span>', либо '<span class="tex-font-style-tt">1</span>') выписали все пары подряд идущих символов (все подстроки длины $$$2$$$). Для каждой пары (подстроки длины $$$2$$$) посчитали количество символов '<span class="tex-font-style-tt">1</span>' (единиц) в ней.</p><p>Вам заданы три числа:</p><ul> <li> $$$n_0$$$ — количество пар подряд идущих символов (подстрок), в которых $$$0$$$ единиц; </li><li> $$$n_1$$$ — количество пар подряд идущих символов (подстрок), в которых $$$1$$$ единица; </li><li> $$$n_2$$$ — количество пар подряд идущих символов (подстрок), в которых $$$2$$$ единицы. </li></ul><p>Например, для строки $$$s=$$$«<span class="tex-font-style-tt">1110011110</span>» были бы выписаны следующие подстроки: «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">10</span>», «<span class="tex-font-style-tt">00</span>», «<span class="tex-font-style-tt">01</span>», «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">11</span>», «<span class="tex-font-style-tt">10</span>». Таким образом, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.</p><p>Ваша задача — по заданным $$$n_0, n_1, n_2$$$ восстановить <span class="tex-font-style-bf">любую</span> подходящую 01-строку (бинарную строку) $$$s$$$. Гарантируется, что хотя бы одно из чисел $$$n_0, n_1, n_2$$$ отлично от $$$0$$$. Также гарантируется, что решение существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее во входных данных записаны сами наборы.</p><p>Каждый набор состоит из одной строки, которая содержит три целых числа $$$n_0, n_1, n_2$$$ ($$$0 \le n_0, n_1, n_2 \le 100$$$; $$$n_0 + n_1 + n_2 &gt; 0$$$). Гарантируется, что ответ для заданных $$$n_0, n_1, n_2$$$ существует.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Каждая из строк должна содержать ответ в виде 01-строки (бинарной строки) на соответствующий набор входных данных. Если возможных ответов несколько, выведите любой из них.</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 3 5 1 1 1 3 9 3 0 1 0 3 1 2 0 0 3 2 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1110011110 0011 0110001100101011 10 0000111 1111 000 </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 11:03: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:'8124a09b8a0b162e',t:'MTY5NjY2NTgwNi44OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\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"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*1500"]
1352G
1352
G
ru
G. Особая перестановка
<div class="problem-statement"><div class="header"><div class="title">G. Особая перестановка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Перестановкой длины $$$n$$$ называется такой массив $$$p=[p_1,p_2,\dots,p_n]$$$, который содержит каждое число от $$$1$$$ до $$$n$$$ (включительно) и притом ровно по одному разу. Например, $$$p=[3,1,4,2,5]$$$ — перестановка длины $$$5$$$.</p><p>Для заданного числа $$$n$$$ ($$$n \ge 2$$$) найдите такую перестановку $$$p$$$, в которой разница (то есть модуль разности) любых двух соседних элементов находится в диапазоне от $$$2$$$ до $$$4$$$, включительно. Формально, для перестановки $$$p$$$ должно выполняться $$$2 \le |p_i - p_{i+1}| \le 4$$$ для всех $$$i$$$ ($$$1 \le i &lt; n$$$).</p><p>Выведите любую такую перестановку для заданного значения $$$n$$$ или определите, что ее не существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Каждый набор описывается единственной строкой, в которой содержится целое число $$$n$$$ ($$$2 \le n \le 1000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Очередная строка должна содержать <span class="tex-font-style-tt">-1</span>, если для соответствующего набора входных данных искомой перестановки не существует. В противном случае выведите искомую перестановку. Если таких перестановок существует несколько, то выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 10 2 4 6 7 13 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 6 10 8 4 7 3 1 5 2 -1 3 1 4 2 5 3 6 2 4 1 5 1 3 6 2 4 7 13 9 7 11 8 4 1 3 5 2 6 10 12 </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="c405d19231297906a05bf563cf3d0486"/> <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="a93983fc9e9a8c248f6350731e5df450cf7f9733"/> <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='c405d19231297906a05bf563cf3d0486'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1352%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='c405d19231297906a05bf563cf3d0486'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1352">Codeforces Round 640 (Div. 4)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='c405d19231297906a05bf563cf3d0486'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1352/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='c405d19231297906a05bf563cf3d0486'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="616899"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c405d19231297906a05bf563cf3d0486'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="616899"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77130" title="77130" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15627" resourceName="77130" resourceManual="true" src="//codeforces.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/77161" title="77161" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="15628" resourceName="77161" resourceManual="true" src="//codeforces.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/1352">Задачи</a></li> <li><a href="/contest/1352/submit">Отослать</a></li> <li><a href="/contest/1352/my">Мои посылки</a></li> <li><a href="/contest/1352/status">Статус</a></li> <li><a href="/contest/1352/hacks">Взломы</a></li> <li><a href="/contest/1352/standings">Положение</a></li> <li><a href="/contest/1352/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_fc2336eb9934b6a1c866de9793a94134d12fa090"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Особая перестановка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Перестановкой длины $$$n$$$ называется такой массив $$$p=[p_1,p_2,\dots,p_n]$$$, который содержит каждое число от $$$1$$$ до $$$n$$$ (включительно) и притом ровно по одному разу. Например, $$$p=[3,1,4,2,5]$$$ — перестановка длины $$$5$$$.</p><p>Для заданного числа $$$n$$$ ($$$n \ge 2$$$) найдите такую перестановку $$$p$$$, в которой разница (то есть модуль разности) любых двух соседних элементов находится в диапазоне от $$$2$$$ до $$$4$$$, включительно. Формально, для перестановки $$$p$$$ должно выполняться $$$2 \le |p_i - p_{i+1}| \le 4$$$ для всех $$$i$$$ ($$$1 \le i &lt; n$$$).</p><p>Выведите любую такую перестановку для заданного значения $$$n$$$ или определите, что ее не существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Каждый набор описывается единственной строкой, в которой содержится целое число $$$n$$$ ($$$2 \le n \le 1000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Очередная строка должна содержать <span class="tex-font-style-tt">-1</span>, если для соответствующего набора входных данных искомой перестановки не существует. В противном случае выведите искомую перестановку. Если таких перестановок существует несколько, то выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 10 2 4 6 7 13 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 6 10 8 4 7 3 1 5 2 -1 3 1 4 2 5 3 6 2 4 1 5 1 3 6 2 4 7 13 9 7 11 8 4 1 3 5 2 6 10 12 </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 11:03: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:'8124a0b4cbfc163a',t:'MTY5NjY2NTgwOC4xNzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*1600"]
1353A
1353
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$$$ и $$$m$$$. Вам нужно построить массив $$$a$$$ длины $$$n$$$ состоящий из <span class="tex-font-style-bf">неотрицательных целых чисел</span> (т.е. целых чисел больших или равных нулю) такой, что сумма элементов этого массива <span class="tex-font-style-bf">в точности</span> равна $$$m$$$ и величина $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ максимально возможная. Напомним, что $$$|x|$$$ — абсолютное значение $$$x$$$.</p><p>Другими словами, вы хотите максимизировать сумму абсолютных разностей между соседними (последовательными) элементами. Например, если массив $$$a=[1, 3, 2, 5, 5, 0]$$$, то величина, описанная выше, для этого массива равна $$$|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$$$. Заметьте, что этот пример <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 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — длину массива и его сумму соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — максимально возможное значение $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ для массива $$$a$$$, состоящего из $$$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> 5 1 100 2 2 5 5 2 1000000000 1000000000 1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 2 10 1000000000 2000000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера единственный возможный массив — $$$[100]$$$, и ответ очевидно равен $$$0$$$.</p><p>Во втором наборе тестовых данных примера один из возможных массивов — $$$[2, 0]$$$, и ответ равен $$$|2-0| = 2$$$.</p><p>В третьем наборе тестовых данных примера один из возможных массивов — $$$[0, 2, 0, 3, 0]$$$, и ответ равен $$$|0-2| + |2-0| + |0-3| + |3-0| = 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="92f0d4efd14fd72cb402a62f6dd1a89c"/> <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="134b039cb4ec8c6d4592abffb422fda7ed92ea33"/> <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='92f0d4efd14fd72cb402a62f6dd1a89c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1353%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='92f0d4efd14fd72cb402a62f6dd1a89c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1353">Codeforces Round 642 (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='92f0d4efd14fd72cb402a62f6dd1a89c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1353/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='92f0d4efd14fd72cb402a62f6dd1a89c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="620787"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='92f0d4efd14fd72cb402a62f6dd1a89c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="620787"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77309" title="Codeforces Round #642 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10943" resourceName="Codeforces Round #642 (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/77373" title="Codeforces Round #642 (Div. 3) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10944" resourceName="Codeforces Round #642 (Div. 3) 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/1353">Задачи</a></li> <li><a href="/contest/1353/submit">Отослать</a></li> <li><a href="/contest/1353/my">Мои посылки</a></li> <li><a href="/contest/1353/status">Статус</a></li> <li><a href="/contest/1353/hacks">Взломы</a></li> <li><a href="/contest/1353/standings">Положение</a></li> <li><a href="/contest/1353/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a3ff900588d92fffb016be6d393ade5332d05293"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ и $$$m$$$. Вам нужно построить массив $$$a$$$ длины $$$n$$$ состоящий из <span class="tex-font-style-bf">неотрицательных целых чисел</span> (т.е. целых чисел больших или равных нулю) такой, что сумма элементов этого массива <span class="tex-font-style-bf">в точности</span> равна $$$m$$$ и величина $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ максимально возможная. Напомним, что $$$|x|$$$ — абсолютное значение $$$x$$$.</p><p>Другими словами, вы хотите максимизировать сумму абсолютных разностей между соседними (последовательными) элементами. Например, если массив $$$a=[1, 3, 2, 5, 5, 0]$$$, то величина, описанная выше, для этого массива равна $$$|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$$$. Заметьте, что этот пример <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 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — длину массива и его сумму соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — максимально возможное значение $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ для массива $$$a$$$, состоящего из $$$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> 5 1 100 2 2 5 5 2 1000000000 1000000000 1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 2 10 1000000000 2000000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера единственный возможный массив — $$$[100]$$$, и ответ очевидно равен $$$0$$$.</p><p>Во втором наборе тестовых данных примера один из возможных массивов — $$$[2, 0]$$$, и ответ равен $$$|2-0| = 2$$$.</p><p>В третьем наборе тестовых данных примера один из возможных массивов — $$$[0, 2, 0, 3, 0]$$$, и ответ равен $$$|0-2| + |2-0| + |0-3| + |3-0| = 10$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:03: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:'8124a0bccac27b43',t:'MTY5NjY2NTgwOS42MTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"]
1353B
1353
B
ru
B. Два массива и обмены
<div class="problem-statement"><div class="header"><div class="title">B. Два массива и обмены</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два массива $$$a$$$ и $$$b$$$, оба состоят из $$$n$$$ положительных (больших нуля) целых чисел. Также вам задано число $$$k$$$.</p><p>За один ход вы можете выбрать два индекса $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$) и поменять местами $$$a_i$$$ и $$$b_j$$$ (i.e. $$$a_i$$$ становится $$$b_j$$$ и наоборот). Заметьте, что $$$i$$$ и $$$j$$$ могут совпадать или отличаться (в частности, обмен $$$a_2$$$ с $$$b_2$$$ или обмен $$$a_3$$$ с $$$b_9$$$ оба считаются приемлемыми ходами).</p><p>Ваша задача — назвать <span class="tex-font-style-bf">максимальную</span> возможную сумму, которую вы можете получить в массиве $$$a$$$, если вы сделаете не более $$$k$$$ таких ходов (обменов).</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 200$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 30; 0 \le k \le n$$$) — количество элементов в $$$a$$$ и $$$b$$$ и максимальное количество ходов, которое вы можете сделать. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 30$$$), где $$$a_i$$$ — это $$$i$$$-й элемент в $$$a$$$. Третья строка набора тестовых данных содержит $$$n$$$ целых чисел $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 30$$$), где $$$b_i$$$ — это $$$i$$$-й элемент в $$$b$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — <span class="tex-font-style-bf">максимальную</span> возможную сумму, которую вы можете получить в массиве $$$a$$$, если вы можете совершить не более $$$k$$$ обменов.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 1 1 2 3 4 5 5 5 5 6 6 5 1 2 5 4 3 5 3 1 2 3 4 5 10 9 10 10 9 4 0 2 2 4 3 2 4 2 3 4 4 1 2 2 1 4 4 5 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 27 39 11 17 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера вы можете поменять местами $$$a_1 = 1$$$ и $$$b_2 = 4$$$ и тогда получите $$$a=[4, 2]$$$ и $$$b=[3, 1]$$$.</p><p>Во втором наборе тестовых данных примера вам не нужно ничего менять.</p><p>В третьем наборе тестовых данных примера вы можете поменять местами $$$a_1 = 1$$$ и $$$b_1 = 10$$$, $$$a_3 = 3$$$ и $$$b_3 = 10$$$ и $$$a_2 = 2$$$ и $$$b_4 = 10$$$, и получить $$$a=[10, 10, 10, 4, 5]$$$ и $$$b=[1, 9, 3, 2, 9]$$$.</p><p>В четвертом наборе тестовых данных примера вы не можете ничего поменять.</p><p>В пятом наборе тестовых данных примера вы можете поменять местами массивы $$$a$$$ и $$$b$$$ и получить $$$a=[4, 4, 5, 4]$$$ и $$$b=[1, 2, 2, 1]$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f23502de2ae331664cf147325b1d9890"/> <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="134b039cb4ec8c6d4592abffb422fda7ed92ea33"/> <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='f23502de2ae331664cf147325b1d9890'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1353%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='f23502de2ae331664cf147325b1d9890'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1353">Codeforces Round 642 (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='f23502de2ae331664cf147325b1d9890'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1353/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='f23502de2ae331664cf147325b1d9890'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="620788"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f23502de2ae331664cf147325b1d9890'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="620788"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77309" title="Codeforces Round #642 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10943" resourceName="Codeforces Round #642 (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/77373" title="Codeforces Round #642 (Div. 3) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10944" resourceName="Codeforces Round #642 (Div. 3) 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/1353">Задачи</a></li> <li><a href="/contest/1353/submit">Отослать</a></li> <li><a href="/contest/1353/my">Мои посылки</a></li> <li><a href="/contest/1353/status">Статус</a></li> <li><a href="/contest/1353/hacks">Взломы</a></li> <li><a href="/contest/1353/standings">Положение</a></li> <li><a href="/contest/1353/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_80ed1f36f3304b88e9110b8a2de9531cc3eeb5d8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Два массива и обмены</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два массива $$$a$$$ и $$$b$$$, оба состоят из $$$n$$$ положительных (больших нуля) целых чисел. Также вам задано число $$$k$$$.</p><p>За один ход вы можете выбрать два индекса $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$) и поменять местами $$$a_i$$$ и $$$b_j$$$ (i.e. $$$a_i$$$ становится $$$b_j$$$ и наоборот). Заметьте, что $$$i$$$ и $$$j$$$ могут совпадать или отличаться (в частности, обмен $$$a_2$$$ с $$$b_2$$$ или обмен $$$a_3$$$ с $$$b_9$$$ оба считаются приемлемыми ходами).</p><p>Ваша задача — назвать <span class="tex-font-style-bf">максимальную</span> возможную сумму, которую вы можете получить в массиве $$$a$$$, если вы сделаете не более $$$k$$$ таких ходов (обменов).</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 200$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 30; 0 \le k \le n$$$) — количество элементов в $$$a$$$ и $$$b$$$ и максимальное количество ходов, которое вы можете сделать. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 30$$$), где $$$a_i$$$ — это $$$i$$$-й элемент в $$$a$$$. Третья строка набора тестовых данных содержит $$$n$$$ целых чисел $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 30$$$), где $$$b_i$$$ — это $$$i$$$-й элемент в $$$b$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него — <span class="tex-font-style-bf">максимальную</span> возможную сумму, которую вы можете получить в массиве $$$a$$$, если вы можете совершить не более $$$k$$$ обменов.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 1 1 2 3 4 5 5 5 5 6 6 5 1 2 5 4 3 5 3 1 2 3 4 5 10 9 10 10 9 4 0 2 2 4 3 2 4 2 3 4 4 1 2 2 1 4 4 5 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 27 39 11 17 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера вы можете поменять местами $$$a_1 = 1$$$ и $$$b_2 = 4$$$ и тогда получите $$$a=[4, 2]$$$ и $$$b=[3, 1]$$$.</p><p>Во втором наборе тестовых данных примера вам не нужно ничего менять.</p><p>В третьем наборе тестовых данных примера вы можете поменять местами $$$a_1 = 1$$$ и $$$b_1 = 10$$$, $$$a_3 = 3$$$ и $$$b_3 = 10$$$ и $$$a_2 = 2$$$ и $$$b_4 = 10$$$, и получить $$$a=[10, 10, 10, 4, 5]$$$ и $$$b=[1, 9, 3, 2, 9]$$$.</p><p>В четвертом наборе тестовых данных примера вы не можете ничего поменять.</p><p>В пятом наборе тестовых данных примера вы можете поменять местами массивы $$$a$$$ и $$$b$$$ и получить $$$a=[4, 4, 5, 4]$$$ и $$$b=[1, 2, 2, 1]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:03: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:'8124a0c5ecf41607',t:'MTY5NjY2NTgxMS4wMTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*800"]
1353C
1353
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 \times n$$$, где $$$n$$$ <span class="tex-font-style-bf">нечетно</span> (не кратно $$$2$$$). Изначально в каждой клетке доски расположена одна фигура.</p><p>За один ход вы можете выбрать <span class="tex-font-style-bf">ровно одну фигуру</span>, расположенную в какой-либо клетке и передвинуть ее в одну из клеток, <span class="tex-font-style-bf">имеющую общую сторону или угол с текущей клеткой</span>, то есть из клетки $$$(i, j)$$$ вы можете передвинуть фигуру в клетку: </p><ul> <li> $$$(i - 1, j - 1)$$$; </li><li> $$$(i - 1, j)$$$; </li><li> $$$(i - 1, j + 1)$$$; </li><li> $$$(i, j - 1)$$$; </li><li> $$$(i, j + 1)$$$; </li><li> $$$(i + 1, j - 1)$$$; </li><li> $$$(i + 1, j)$$$; </li><li> $$$(i + 1, j + 1)$$$; </li></ul><p>Конечно же, вы <span class="tex-font-style-bf">не можете</span> двигать фигуры в клетки за пределами доски. Допустимо, что после хода в одной клетке будет находиться несколько фигур.</p><p>Ваша задача — найти минимальное количество ходов, необходимое, чтобы собрать <span class="tex-font-style-bf">все фигуры</span> в <span class="tex-font-style-bf">одной</span> клетке (т.е. в $$$n^2-1$$$ клетках должно быть расположено $$$0$$$ фигур и в одной клетке должны быть расположены $$$n^2$$$ фигур).</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 200$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — размер доски. Гарантируется, что $$$n$$$ нечетно (не делится на $$$2$$$).</p><p>Также гарантируется, что сумма $$$n$$$ по всем наборам тестовых данных не превосходит $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ — минимальное количество ходов, необходимое, чтобы собрать <span class="tex-font-style-bf">все фигуры</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> 3 1 5 499993 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 40 41664916690999888 </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="bd442563890813c47a9e0c2c317b2ccb"/> <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="134b039cb4ec8c6d4592abffb422fda7ed92ea33"/> <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='bd442563890813c47a9e0c2c317b2ccb'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1353%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='bd442563890813c47a9e0c2c317b2ccb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1353">Codeforces Round 642 (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='bd442563890813c47a9e0c2c317b2ccb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1353/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='bd442563890813c47a9e0c2c317b2ccb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="620789"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bd442563890813c47a9e0c2c317b2ccb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="620789"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77309" title="Codeforces Round #642 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10943" resourceName="Codeforces Round #642 (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/77373" title="Codeforces Round #642 (Div. 3) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10944" resourceName="Codeforces Round #642 (Div. 3) 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/1353">Задачи</a></li> <li><a href="/contest/1353/submit">Отослать</a></li> <li><a href="/contest/1353/my">Мои посылки</a></li> <li><a href="/contest/1353/status">Статус</a></li> <li><a href="/contest/1353/hacks">Взломы</a></li> <li><a href="/contest/1353/standings">Положение</a></li> <li><a href="/contest/1353/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_aa0a6ebe59ab4f3843109cf8cedba523b2dca4a0"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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 \times n$$$, где $$$n$$$ <span class="tex-font-style-bf">нечетно</span> (не кратно $$$2$$$). Изначально в каждой клетке доски расположена одна фигура.</p><p>За один ход вы можете выбрать <span class="tex-font-style-bf">ровно одну фигуру</span>, расположенную в какой-либо клетке и передвинуть ее в одну из клеток, <span class="tex-font-style-bf">имеющую общую сторону или угол с текущей клеткой</span>, то есть из клетки $$$(i, j)$$$ вы можете передвинуть фигуру в клетку: </p><ul> <li> $$$(i - 1, j - 1)$$$; </li><li> $$$(i - 1, j)$$$; </li><li> $$$(i - 1, j + 1)$$$; </li><li> $$$(i, j - 1)$$$; </li><li> $$$(i, j + 1)$$$; </li><li> $$$(i + 1, j - 1)$$$; </li><li> $$$(i + 1, j)$$$; </li><li> $$$(i + 1, j + 1)$$$; </li></ul><p>Конечно же, вы <span class="tex-font-style-bf">не можете</span> двигать фигуры в клетки за пределами доски. Допустимо, что после хода в одной клетке будет находиться несколько фигур.</p><p>Ваша задача — найти минимальное количество ходов, необходимое, чтобы собрать <span class="tex-font-style-bf">все фигуры</span> в <span class="tex-font-style-bf">одной</span> клетке (т.е. в $$$n^2-1$$$ клетках должно быть расположено $$$0$$$ фигур и в одной клетке должны быть расположены $$$n^2$$$ фигур).</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 200$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — размер доски. Гарантируется, что $$$n$$$ нечетно (не делится на $$$2$$$).</p><p>Также гарантируется, что сумма $$$n$$$ по всем наборам тестовых данных не превосходит $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ — минимальное количество ходов, необходимое, чтобы собрать <span class="tex-font-style-bf">все фигуры</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> 3 1 5 499993 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 40 41664916690999888 </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 11:03: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:'8124a0ce7f2c4d90',t:'MTY5NjY2NTgxMi4zNDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1000"]
1353D
1353
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>Вам задана массив $$$a$$$ длины $$$n$$$, состоящий из нулей. Вы выполняете $$$n$$$ действий с этим массивом: в течение $$$i$$$-го действия происходит следующая последовательность операций:</p><ol> <li> Выбирается максимальный по длине подмассив (<span class="tex-font-style-bf">последовательный подотрезок</span>), состоящий <span class="tex-font-style-bf">только</span> из нулей, среди всех таких отрезков выбирается <span class="tex-font-style-bf">самый левый</span>; </li><li> Пусть этот отрезок равен $$$[l; r]$$$. Если $$$r-l+1$$$ нечетно (не делится на $$$2$$$), то присваивается $$$a[\frac{l+r}{2}] := i$$$ (где $$$i$$$ — номер текущего действия), иначе (если $$$r-l+1$$$ четно) присваивается $$$a[\frac{l+r-1}{2}] := i$$$. </li></ol><p>Рассмотрим массив $$$a$$$ длины $$$5$$$ (изачально $$$a=[0, 0, 0, 0, 0]$$$). Тогда он меняется следующим образом:</p><ol> <li> Сначала мы выбираем отрезок $$$[1; 5]$$$ и присваиваем $$$a[3] := 1$$$, таким образом $$$a$$$ становится равен $$$[0, 0, 1, 0, 0]$$$; </li><li> затем мы выбираем отрезок $$$[1; 2]$$$ и присваиваем $$$a[1] := 2$$$, таким образом $$$a$$$ становится равен $$$[2, 0, 1, 0, 0]$$$; </li><li> затем мы выбираем отрезок $$$[4; 5]$$$ и присваиваем $$$a[4] := 3$$$, таким образом $$$a$$$ становится равен $$$[2, 0, 1, 3, 0]$$$; </li><li> затем мы выбираем отрезок $$$[2; 2]$$$ и присваиваем $$$a[2] := 4$$$, таким образом $$$a$$$ становится равен $$$[2, 4, 1, 3, 0]$$$; </li><li> и наконец мы выбираем отрезок $$$[5; 5]$$$ и присваиваем $$$a[5] := 5$$$, таким образом $$$a$$$ становится равен $$$[2, 4, 1, 3, 5]$$$. </li></ol><p>Ваша задача — найти массив $$$a$$$ длины $$$n$$$ после выполнения всех $$$n$$$ действий. <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 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длину $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ — массив $$$a$$$ длины $$$n$$$ после выполнения $$$n$$$ действий, описанных в условии задачи. <span class="tex-font-style-bf">Заметьте, что ответ существует и единственен</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 3 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 2 1 3 3 1 2 4 2 4 1 3 5 3 4 1 5 2 6 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="04cd8887da9209b688fca3afc3c4f3cd"/> <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="134b039cb4ec8c6d4592abffb422fda7ed92ea33"/> <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='04cd8887da9209b688fca3afc3c4f3cd'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1353%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='04cd8887da9209b688fca3afc3c4f3cd'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1353">Codeforces Round 642 (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='04cd8887da9209b688fca3afc3c4f3cd'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1353/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='04cd8887da9209b688fca3afc3c4f3cd'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="620790"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='04cd8887da9209b688fca3afc3c4f3cd'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="620790"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77309" title="Codeforces Round #642 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10943" resourceName="Codeforces Round #642 (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/77373" title="Codeforces Round #642 (Div. 3) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10944" resourceName="Codeforces Round #642 (Div. 3) 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/1353">Задачи</a></li> <li><a href="/contest/1353/submit">Отослать</a></li> <li><a href="/contest/1353/my">Мои посылки</a></li> <li><a href="/contest/1353/status">Статус</a></li> <li><a href="/contest/1353/hacks">Взломы</a></li> <li><a href="/contest/1353/standings">Положение</a></li> <li><a href="/contest/1353/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cc705bddcd15e7548efed9b9cbbd88a989158330"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам задана массив $$$a$$$ длины $$$n$$$, состоящий из нулей. Вы выполняете $$$n$$$ действий с этим массивом: в течение $$$i$$$-го действия происходит следующая последовательность операций:</p><ol> <li> Выбирается максимальный по длине подмассив (<span class="tex-font-style-bf">последовательный подотрезок</span>), состоящий <span class="tex-font-style-bf">только</span> из нулей, среди всех таких отрезков выбирается <span class="tex-font-style-bf">самый левый</span>; </li><li> Пусть этот отрезок равен $$$[l; r]$$$. Если $$$r-l+1$$$ нечетно (не делится на $$$2$$$), то присваивается $$$a[\frac{l+r}{2}] := i$$$ (где $$$i$$$ — номер текущего действия), иначе (если $$$r-l+1$$$ четно) присваивается $$$a[\frac{l+r-1}{2}] := i$$$. </li></ol><p>Рассмотрим массив $$$a$$$ длины $$$5$$$ (изачально $$$a=[0, 0, 0, 0, 0]$$$). Тогда он меняется следующим образом:</p><ol> <li> Сначала мы выбираем отрезок $$$[1; 5]$$$ и присваиваем $$$a[3] := 1$$$, таким образом $$$a$$$ становится равен $$$[0, 0, 1, 0, 0]$$$; </li><li> затем мы выбираем отрезок $$$[1; 2]$$$ и присваиваем $$$a[1] := 2$$$, таким образом $$$a$$$ становится равен $$$[2, 0, 1, 0, 0]$$$; </li><li> затем мы выбираем отрезок $$$[4; 5]$$$ и присваиваем $$$a[4] := 3$$$, таким образом $$$a$$$ становится равен $$$[2, 0, 1, 3, 0]$$$; </li><li> затем мы выбираем отрезок $$$[2; 2]$$$ и присваиваем $$$a[2] := 4$$$, таким образом $$$a$$$ становится равен $$$[2, 4, 1, 3, 0]$$$; </li><li> и наконец мы выбираем отрезок $$$[5; 5]$$$ и присваиваем $$$a[5] := 5$$$, таким образом $$$a$$$ становится равен $$$[2, 4, 1, 3, 5]$$$. </li></ol><p>Ваша задача — найти массив $$$a$$$ длины $$$n$$$ после выполнения всех $$$n$$$ действий. <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 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длину $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам тестовых данных не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ — массив $$$a$$$ длины $$$n$$$ после выполнения $$$n$$$ действий, описанных в условии задачи. <span class="tex-font-style-bf">Заметьте, что ответ существует и единственен</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 3 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 2 1 3 3 1 2 4 2 4 1 3 5 3 4 1 5 2 6 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:03: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:'8124a0d6ea903aa1',t:'MTY5NjY2NTgxMy43MjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\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", "*1600"]
1353E
1353
E
ru
E. К-периодичная гирлянда
<div class="problem-statement"><div class="header"><div class="title">E. К-периодичная гирлянда</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана гирлянда, состоящая из $$$n$$$ ламп. Состояния ламп описываются строкой $$$s$$$ длины $$$n$$$. $$$i$$$-й символ строки $$$s_i$$$ равен '<span class="tex-font-style-tt">0</span>', если $$$i$$$-я лампа выключена, или '<span class="tex-font-style-tt">1</span>', если $$$i$$$-я лампа включена. Вам также задано положительное целое число $$$k$$$.</p><p>За один ход вы можете выбрать <span class="tex-font-style-bf">одну лампу</span> и изменить ее состояние (то есть включить ее, если она выключена, и наоборот).</p><p>Гирлянда называется $$$k$$$-периодичной, если расстояние между <span class="tex-font-style-bf">каждой парой соседних включенных ламп</span> равно <span class="tex-font-style-bf">в точности</span> $$$k$$$. Рассмотрим случай $$$k=3$$$. Тогда гирлянды «<span class="tex-font-style-tt">00010010</span>», «<span class="tex-font-style-tt">1001001</span>», «<span class="tex-font-style-tt">00010</span>» и «<span class="tex-font-style-tt">0</span>» являются хорошими, а гирлянды «<span class="tex-font-style-tt">00101001</span>», «<span class="tex-font-style-tt">1000001</span>» и «<span class="tex-font-style-tt">01001100</span>» не являются хорошими. Заметьте, что <span class="tex-font-style-bf">гирлянда не является цикличной</span>, то есть первая включенная лампа не идет после последней включенной лампы и наоборот.</p><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое для того, чтобы получить $$$k$$$-периодичную гирлянду из заданной.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 25~ 000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) — длину $$$s$$$ и необходимый период. Вторая строка набора тестовых данных содержит строку $$$s$$$, состоящую из $$$n$$$ символов '<span class="tex-font-style-tt">0</span>' и '<span class="tex-font-style-tt">1</span>'.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам тестовых данных не превосходит $$$10^6$$$ ($$$\sum n \le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ — <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое для того, чтобы получить $$$k$$$-периодичную гирлянду из заданной.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 9 2 010001010 9 3 111100000 7 4 1111111 10 3 1001110101 1 1 1 1 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 5 4 0 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="61eb551ec0660d3c09aee91f0dfff4ba"/> <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="134b039cb4ec8c6d4592abffb422fda7ed92ea33"/> <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='61eb551ec0660d3c09aee91f0dfff4ba'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1353%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='61eb551ec0660d3c09aee91f0dfff4ba'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1353">Codeforces Round 642 (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='61eb551ec0660d3c09aee91f0dfff4ba'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1353/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='61eb551ec0660d3c09aee91f0dfff4ba'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="620791"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='61eb551ec0660d3c09aee91f0dfff4ba'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="620791"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/77309" title="Codeforces Round #642 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10943" resourceName="Codeforces Round #642 (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/77373" title="Codeforces Round #642 (Div. 3) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10944" resourceName="Codeforces Round #642 (Div. 3) 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/1353">Задачи</a></li> <li><a href="/contest/1353/submit">Отослать</a></li> <li><a href="/contest/1353/my">Мои посылки</a></li> <li><a href="/contest/1353/status">Статус</a></li> <li><a href="/contest/1353/hacks">Взломы</a></li> <li><a href="/contest/1353/standings">Положение</a></li> <li><a href="/contest/1353/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0a6479caf95f2a66fc71eb6b2aef62ca5cfed5e8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. К-периодичная гирлянда</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана гирлянда, состоящая из $$$n$$$ ламп. Состояния ламп описываются строкой $$$s$$$ длины $$$n$$$. $$$i$$$-й символ строки $$$s_i$$$ равен '<span class="tex-font-style-tt">0</span>', если $$$i$$$-я лампа выключена, или '<span class="tex-font-style-tt">1</span>', если $$$i$$$-я лампа включена. Вам также задано положительное целое число $$$k$$$.</p><p>За один ход вы можете выбрать <span class="tex-font-style-bf">одну лампу</span> и изменить ее состояние (то есть включить ее, если она выключена, и наоборот).</p><p>Гирлянда называется $$$k$$$-периодичной, если расстояние между <span class="tex-font-style-bf">каждой парой соседних включенных ламп</span> равно <span class="tex-font-style-bf">в точности</span> $$$k$$$. Рассмотрим случай $$$k=3$$$. Тогда гирлянды «<span class="tex-font-style-tt">00010010</span>», «<span class="tex-font-style-tt">1001001</span>», «<span class="tex-font-style-tt">00010</span>» и «<span class="tex-font-style-tt">0</span>» являются хорошими, а гирлянды «<span class="tex-font-style-tt">00101001</span>», «<span class="tex-font-style-tt">1000001</span>» и «<span class="tex-font-style-tt">01001100</span>» не являются хорошими. Заметьте, что <span class="tex-font-style-bf">гирлянда не является цикличной</span>, то есть первая включенная лампа не идет после последней включенной лампы и наоборот.</p><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое для того, чтобы получить $$$k$$$-периодичную гирлянду из заданной.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 25~ 000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) — длину $$$s$$$ и необходимый период. Вторая строка набора тестовых данных содержит строку $$$s$$$, состоящую из $$$n$$$ символов '<span class="tex-font-style-tt">0</span>' и '<span class="tex-font-style-tt">1</span>'.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам тестовых данных не превосходит $$$10^6$$$ ($$$\sum n \le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ — <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое для того, чтобы получить $$$k$$$-периодичную гирлянду из заданной.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 9 2 010001010 9 3 111100000 7 4 1111111 10 3 1001110101 1 1 1 1 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 5 4 0 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 11:03: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:'8124a0df998913b4',t:'MTY5NjY2NTgxNS4wODEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1900"]