After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
中文翻譯
在課程結束後,n 組學生決定去拜訪 Polycarpus 來慶祝他的生日,我們知道第 i 組學生包含了 si 位朋友 (1 ≤ si ≤ 4),而且他們會一起前往 Polycarpus 那。他們決定要搭計程車來前往,每一台車最多可以載 4 位乘客。現在要計算最少的計程車數來讓所有的學生組別可以每組都在同一台車上(但一台計程車可以載超過一組學生)
輸入
The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, …, sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.
第一行包含了整數 n (1 ≤ n ≤ 105) — 學生群組的數量。第二行包含了一個整數序列 s1, s2, …, sn (1 ≤ si ≤ 4)。這些整數由空白間隔,si 就是第 i 組學生的人數。
輸出
Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.
整體邏輯上來說沒問題,但卻超過程式的時限,畢竟在 for loop 裡面又去indexOf,最少也是個 O(n2)
C#解決方案
第一次嘗試 – 超時 Time limit exceeded
int n = int.Parse(Console.ReadLine()); //number of groups
int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
int carCnt = 0;
for(int i=0; i<arr.Length;i++){
int num = arr[i]; // number of children in the group
if(num==4){
carCnt+=1;
arr[i] = 0;
}
else if(num==3){
var idx = Array.IndexOf(arr,1);
if(idx>-1){
carCnt+=1;
arr[i] = 0;
arr[idx] = 0;
}
}
else if(num==2){
var idx = Array.LastIndexOf(arr,2);
if(idx>-1 && idx != i){
carCnt+=1;
arr[i] = 0;
arr[idx] = 0;
continue;
}
idx = Array.IndexOf(arr,1);
if(idx>-1){
arr[i] = 0;
arr[idx] = 3;
}
}
else if(num==1) {
var idx = Array.IndexOf(arr,3);
if(idx>-1){
carCnt+=1;
arr[i] = 0;
arr[idx] = 0;
continue;
}
idx = Array.LastIndexOf(arr,2);
if(idx>-1){
arr[i] = 0;
arr[idx] = 3;
continue;
}
idx = Array.LastIndexOf(arr,1);
if(idx>-1 && idx != i){
arr[i] = 0;
arr[idx] = 2;
continue;
}
}
}
int nonZeroCount = arr.Count(x => x > 0);
Console.WriteLine(carCnt+nonZeroCount);
思考後修正了整個寫法
畢竟對於要怎麼計算其實是知道的 (湊成一車)
那我們幹嘛執著於 index呢,這樣還要浪費時間來多進行判斷
故很快就修正了寫法
方案1
int n = int.Parse(Console.ReadLine()); //number of groups
int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
int carCnt = 0;
int cnt1 = 0;
int cnt2 = 0;
int cnt3 = 0;
foreach(var a in arr){
if(a==1){
cnt1+=1;
}
else if(a==2){
cnt2+=1;
}
else if(a==3){
cnt3+=1;
}
else{ //4
carCnt+=1;
}
}
while(cnt3>0 && cnt1>0){
cnt3-=1;
cnt1-=1;
carCnt+=1;
}
while(cnt1>1){
cnt1-=2;
cnt2+=1;
}
while(cnt2>1){
cnt2-=2;
carCnt+=1;
}
// If there is exactly one cnt1 and one cnt2, they can be combined into one taxi
if(cnt1==1 && cnt2==1){
Console.WriteLine(carCnt+1+cnt3);
}
else{
Console.WriteLine(carCnt+cnt1+cnt2+cnt3);
}
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"6740fd2c82"};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"6740fd2c82","uagb_grid_ajax_nonce":"2503a26f73"};
( function() {
let elements = document.querySelectorAll( '.uagb-post-grid.uagb-block-567f2d62 .uagb-post-pagination-wrap a' );
elements.forEach(function(element) {
element.addEventListener("click", function(event){
event.preventDefault();
const link = event.target.getAttribute('href').match( /\/page\/\d+\// )?.[0] || '';
const regex = /\d+/; // regular expression to match a number at the end of the string
const match = link.match( regex ) ? link.match( regex )[0] : 1; // match the regular expression with the link
const pageNumber = parseInt( match ); // extract the number and parse it to an integer
window.UAGBPostGrid._callAjax({"btnBorderTopWidth":1,"btnBorderLeftWidth":1,"btnBorderRightWidth":1,"btnBorderBottomWidth":1,"btnBorderTopLeftRadius":30,"btnBorderTopRightRadius":30,"btnBorderBottomLeftRadius":30,"btnBorderBottomRightRadius":30,"btnBorderStyle":"none","overallBorderColor":"","block_id":"567f2d62","categories":"271","displayPostExcerpt":false,"displayPostComment":false,"displayPostImage":false,"imgSize":"medium","linkBox":false,"align":"center","orderBy":"rand","excludeCurrentPost":true,"postPagination":true,"pageLimit":0,"imageRatio":"2-3","imgEqualHeight":true,"UAGHideMob":true,"UAGHideTab":true,"UAGResponsiveConditions":true,"btnBorderLink":true,"btnBorderRadiusLink":true,"overallBorderLink":true,"overallBorderRadiusLink":true,"inheritFromTheme":true,"postType":"post","postDisplaytext":"No post found!","taxonomyType":"category","postsToShow":6,"enableOffset":false,"postsOffset":0,"displayPostDate":true,"excerptLength":15,"displayPostAuthor":false,"displayPostTitle":true,"displayPostTaxonomy":false,"hideTaxonomyIcon":true,"taxStyle":"default","displayPostTaxonomyAboveTitle":"withMeta","imgPosition":"top","bgOverlayColor":"#000000","overlayOpacity":"50","displayPostLink":true,"newTab":false,"ctaText":"Read More","inheritFromThemeBtn":false,"buttonType":"primary","btnHPadding":"","btnVPadding":"","columns":3,"tcolumns":2,"mcolumns":1,"width":"wide","order":"desc","rowGap":20,"rowGapTablet":20,"rowGapMobile":20,"columnGap":20,"bgType":"color","bgColor":"#f6f6f6","titleTag":"h4","titleFontSize":"","titleFontSizeType":"px","titleFontFamily":"","titleLineHeightType":"em","titleLoadGoogleFonts":false,"metaColor":"","highlightedTextColor":"#fff","highlightedTextBgColor":"#3182ce","metaFontSize":"","metaFontSizeType":"px","metaFontFamily":"","metaLineHeightType":"em","metaLoadGoogleFonts":false,"excerptColor":"","excerptFontSize":"","excerptFontSizeType":"px","excerptFontFamily":"","excerptLineHeightType":"em","excerptLoadGoogleFonts":false,"displayPostContentRadio":"excerpt","ctaBgType":"color","ctaBgHType":"color","ctaFontSize":"","ctaFontSizeType":"px","ctaFontFamily":"","ctaLineHeightType":"em","ctaLoadGoogleFonts":false,"paddingTop":20,"paddingBottom":20,"paddingRight":20,"paddingLeft":20,"contentPadding":20,"ctaBottomSpace":0,"ctaBottomSpaceTablet":0,"ctaBottomSpaceMobile":0,"imageBottomSpace":15,"titleBottomSpace":15,"metaBottomSpace":15,"excerptBottomSpace":25,"contentPaddingUnit":"px","rowGapUnit":"px","columnGapUnit":"px","excerptBottomSpaceUnit":"px","paginationSpacingUnit":"px","imageBottomSpaceUnit":"px","titleBottomSpaceUnit":"px","metaBottomSpaceUnit":"px","ctaBottomSpaceUnit":"px","paddingBtnUnit":"px","mobilePaddingBtnUnit":"px","tabletPaddingBtnUnit":"px","paddingUnit":"px","mobilePaddingUnit":"px","tabletPaddingUnit":"px","isPreview":false,"taxDivider":", ","titleLetterSpacing":"","titleLetterSpacingType":"px","metaLetterSpacing":"","metaLetterSpacingType":"px","ctaLetterSpacing":"","ctaLetterSpacingType":"px","excerptLetterSpacing":"","excerptLetterSpacingType":"px","useSeparateBoxShadows":true,"boxShadowColor":"#00000070","boxShadowHOffset":0,"boxShadowVOffset":0,"boxShadowBlur":"","boxShadowSpread":"","boxShadowPosition":"outset","boxShadowColorHover":"","boxShadowHOffsetHover":0,"boxShadowVOffsetHover":0,"boxShadowBlurHover":"","boxShadowSpreadHover":"","boxShadowPositionHover":"outset","borderWidth":"","borderStyle":"none","borderColor":"","borderRadius":"","blockName":"post-grid","equalHeight":true,"paginationBgActiveColor":"#e4e4e4","paginationActiveColor":"#333333","paginationBgColor":"#e4e4e4","paginationColor":"#777777","paginationMarkup":"","paginationLayout":"filled","paginationBorderColor":"#888686","paginationBorderSize":1,"paginationSpacing":20,"paginationAlignment":"left","paginationPrevText":"\u00ab Previous","paginationNextText":"Next \u00bb","layoutConfig":[["uagb\/post-image"],["uagb\/post-taxonomy"],["uagb\/post-title"],["uagb\/post-meta"],["uagb\/post-excerpt"],["uagb\/post-button"]],"post_type":"grid","equalHeightInlineButtons":false,"paginationType":"ajax","isLeftToRightLayout":false,"wrapperTopPadding":"","wrapperRightPadding":"","wrapperLeftPadding":"","wrapperBottomPadding":"","wrapperTopPaddingTablet":"","wrapperRightPaddingTablet":"","wrapperLeftPaddingTablet":"","wrapperBottomPaddingTablet":"","wrapperTopPaddingMobile":"","wrapperRightPaddingMobile":"","wrapperLeftPaddingMobile":"","wrapperBottomPaddingMobile":"","wrapperPaddingUnit":"px","wrapperPaddingUnitTablet":"px","wrapperPaddingUnitMobile":"px","wrapperPaddingLink":false,"wrapperAlign":"row","wrapperAlignPosition":"center","extended_widget_opts_block":{},"extended_widget_opts":{},"extended_widget_opts_state":"","extended_widget_opts_clientid":"","dateUpdated":""}, pageNumber, '567f2d62');
});
});
} )();
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};