Star Arrangements: Difference between revisions

From programming_contest
Jump to navigation Jump to search
imported>Kmk21
Created page with "This problem defines how stars can appear on a flag, then asks us to figure out all valid arrangements. We realize that the input size is small, so we can iterate over all po..."
 
imported>Kmk21
No edit summary
Line 32: Line 32:
[[Category:Implementation Trivial]]
[[Category:Implementation Trivial]]
[[Category:Brute Force]]
[[Category:Brute Force]]
[[Category:Modulus]]

Revision as of 17:14, 30 November 2017

This problem defines how stars can appear on a flag, then asks us to figure out all valid arrangements.

We realize that the input size is small, so we can iterate over all possible arrangements and check if they fit. Note that there are 3 possible arrangements

  1. each row has the same number of stars
  2. rows alternate, and bottom row has same count as top
  3. rows alternate, and bottom row has one fewer than top

Note that for the second two, there is a closed form solution to figure out if the number of stars in the top row will end up fitting the given input. Explicitly iteratively subtracting n, and then n-1 will force an n^2 runtime, which may be too slow.

We can sort the output properly using a custom comparator, or as done here, by traversing the list in a proper order.

import java.util.*;
public class a {
	static Scanner in=new Scanner(System.in);
	public static void main(String[] args) {
		int n=in.nextInt();
		StringBuilder ans=new StringBuilder(String.format("%d:\n",n));
		for(int i=2;i<n;i++) {
			if(n%(i+i-1)==0||(n-i)%(i+i-1)==0)ans.append(String.format("%d,%d\n", i,i-1));
			if(n%i==0)ans.append(String.format("%d,%d\n", i,i));
		}
		System.out.print(ans);
	}
}