The Bitlandians are quite weird people. They have very peculiar customs.
As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.
The kids are excited because just as is customary, they’re going to be paid for the job!
Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.
Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.
Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.
Input
The first line contains integer n (1 ≤ n ≤ 106) — the number of eggs.
Next n lines contain two integers ai and gi each (0 ≤ ai, gi ≤ 1000; ai + gi = 1000): ai is the price said by A. for the i-th egg and gi is the price said by G. for the i-th egg.
Output
If it is impossible to assign the painting, print “-1” (without quotes).
Otherwise print a string, consisting of n letters “G” and “A”. The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter “A” represents A. and letter “G” represents G. If we denote the money Uncle J. must pay A. for the painting as Sa, and the money Uncle J. must pay G. for the painting as Sg, then this inequality must hold: |Sa - Sg| ≤ 500.
If there are several solutions, you are allowed to print any of them.
Examples
Input
2 1 999 999 1
Output
AG
Input
3 400 600 400 600 400 600
Output
AGA
Solution
C# Solution
In my solution,
Start looping through each egg.
For each egg, read the prices named by G. and A. from the input.
Calculate two possible total prices, tmp1 and tmp2:
tmp1 = sum + a, representing the total price if the egg is given to A.
tmp2 = sum – g, representing the total price if the egg is given to G.
Choose the one with a smaller absolute value between tmp1 and tmp2 to minimize the difference in total prices between A. and G., i.e., |sum|.
Update sum with the chosen total price, and mark the selected child (A. or G.) as the recipient of the egg.
Repeat this process until all eggs are assigned.
Finally, check if the absolute value of sum exceeds 500. If yes, it means Uncle J.’s conditions cannot be satisfied, so output “-1”. Otherwise, output the final distribution of eggs.
First try – Time limit exceeded
int n = int.Parse(Console.ReadLine()); //number of eggs
int sum = 0;
string res = "";
for(int i=0; i<n;i++){
string[] arr = Console.ReadLine().Split(' '); //split by space
int a = int.Parse(arr[0]);
int g = int.Parse(arr[1]);
int tmp1 = sum+a;
int tmp2 = sum-g;
if(Math.Abs(tmp1)<Math.Abs(tmp2)){
res+="A";
sum = tmp1;
}
else{
res+="G";
sum = tmp2;
}
}
if(Math.Abs(sum)>500){
Console.WriteLine("-1");
}
else
{
Console.WriteLine(res);
}
The overall logic is correct, but the issue of running for an extended period has arisen.
So, we’ll make some improvements in our next solution.
Firstly, given that the sum of aiand gi always equals 1000, we can replace the line int g = int.Parse(arr[1]); with int g = 1000 – a;.
Secondly, in a loop where string concatenation (+=) is used extensively, it incurs a significant time cost due to copying at each iteration. To address this, we can optimize the process by using a char array instead.
Solution1
int n = int.Parse(Console.ReadLine()); //number of eggs
int sum = 0;
string res = "";
char[] resArr = new char[n];
for(int i=0; i<n;i++){
string[] arr = Console.ReadLine().Split(' '); //split by space
int a = int.Parse(arr[0]);
//int g = int.Parse(arr[1]);
int g = 1000 - a;
int tmp1 = sum+a;
int tmp2 = sum-g;
if(Math.Abs(tmp1)<Math.Abs(tmp2)){
//res+="A";
resArr[i] = 'A';
sum = tmp1;
}
else{
//res+="G";
resArr[i] = 'G';
sum = tmp2;
}
}
if(sum>500 || sum<-500){
Console.WriteLine("-1");
}
else
{
//Console.WriteLine(res);
Console.WriteLine(new string(resArr));
}
And then the solution passed the time constraints! Congratulations!
Java Solution
Solution1
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
int sum = 0;
String res = "";
char[] resArr = new char[n];
for(int i=0; i<n;i++){
String[]arr = scanner.nextLine().split(" "); // split by space
int a = Integer.parseInt(arr[0]);
int g = 1000 - a;
int tmp1 = sum+a;
int tmp2 = sum-g;
if(Math.abs(tmp1)<Math.abs(tmp2)){
resArr[i] = 'A';
sum = tmp1;
}
else{
resArr[i] = 'G';
sum = tmp2;
}
}
if(sum>500 || sum<-500){
System.out.println("-1");
}
else
{
System.out.println(new String(resArr));
}
}
}
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"c29a2a3554"};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"c29a2a3554","uagb_grid_ajax_nonce":"46543fc588"};
( function() {
let elements = document.querySelectorAll( '.uagb-post-grid.uagb-block-613bccac .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({"btnBorderStyle":"none","overallBorderColor":"","block_id":"613bccac","categories":"60","displayPostExcerpt":false,"displayPostComment":false,"displayPostImage":false,"imgSize":"medium","linkBox":false,"orderBy":"rand","excludeCurrentPost":true,"postPagination":true,"pageLimit":0,"imageRatio":"2-3","imgEqualHeight":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","btnHPadding":"","btnVPadding":"","columns":3,"tcolumns":2,"mcolumns":1,"align":"left","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","extended_widget_opts_block":{},"extended_widget_opts":{},"extended_widget_opts_state":"","extended_widget_opts_clientid":"","dateUpdated":""}, pageNumber, '613bccac');
});
});
} )();
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"};