Search Results

Search found 20 results on 1 pages for 'uva'.

Page 1/1 | 1 

  • UVA #10410 Tree Reconstruction

    - by Vincent
    I have worked on UVA 10410 Tree Reconstruction several days. But I can't get the correct answer unitl now. I have used an algorithm similar to the one which we always use to recovery a binary tree through the preorder traversal and the inorder traversal. But it can't work. Can anyone help me? Thanks in advance.

    Read the article

  • UVa #112 Tree Summing

    - by unclerojelio
    I'm working on UVa #112 Tree Summing. I have what I think should be a working solution but it is not accepted by the online judge due to a basic misunderstanding of the problem on my part. Consider the following inputs: -1 (-1()()) 77 (77(1()())()) or diagrammatically, the trees look like: -1 77 / \ / \ () () 1 () / \ () () According to at least two working solutions, the correct output for the above inputs is: yes no However, I don't understand why the second one should be 'no'. It looks to me like the rightmost path of the tree should give the proper sum. What am I missing?

    Read the article

  • 3n+1 problem at UVa

    - by ShahradR
    Hello, I am having trouble with the first question in the Programming Challenges book by Skiena and Revilla. I keep getting a "Wrong Answer" error message, and I don't know why. I've ran my code against the sample input, and I keep getting the right answer. Anyways, if anyone could help me, I would really appreciate it :) Here is the problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=29&page=show_problem&problem=36 And here is the code:` import java.util.Scanner; public class Main { static Scanner kb = new Scanner(System.in); public static void main(String[] args) { while (kb.hasNext()) { long[] numericalInput = {0, 0}; long i = kb.nextLong(); long j = kb.nextLong(); if (i > j) { numericalInput[0] = i; numericalInput[1] = j; } else { numericalInput[0] = j; numericalInput[1] = i; } long maxIterations = 0; for (long n = numericalInput[0]; n <= numericalInput[1]; n += 1) { if (maxIterations < returnIterations(n)) maxIterations = returnIterations(n); } System.out.println(i + " " + j + " " + maxIterations); } System.exit(0); } public static long returnIterations(long num) { long iterations = 0; while (num != 1) { if (num % 2 == 0) num = num / 2; else num = 3 * num + 1; iterations += 1; } iterations += 1; return iterations; } } ` EDIT: I think the problem is with the output. I tried to make it accept all the input first and then display all the answers at once, but I didn't know the terminating condition. I resorted to this method, but I'm not sure that's what the judge wants...

    Read the article

  • Uva's 3n+1 problem

    - by dmindreader
    I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far. import java.io.*; public class NewClass{ /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { int maxCounter= 0; int input; int lowerBound; int upperBound; int counter; int numberOfCycles; int maxCycles= 0; int lowerInt; BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in)); String line = consoleInput.readLine(); String [] splitted = line.split(" "); lowerBound = Integer.parseInt(splitted[0]); upperBound = Integer.parseInt(splitted[1]); int [] recentlyused = new int[1000001]; if (lowerBound > upperBound ) { int h = upperBound; upperBound = lowerBound; lowerBound = h; } lowerInt = lowerBound; while (lowerBound <= upperBound) { counter = lowerBound; numberOfCycles = 0; if (recentlyused[counter] == 0) { while ( counter != 1 ) { if (recentlyused[counter] != 0) { numberOfCycles = recentlyused[counter] + numberOfCycles; counter = 1; } else { if (counter % 2 == 0) { counter = counter /2; } else { counter = 3*counter + 1; } numberOfCycles++; } } } else { numberOfCycles = recentlyused[counter] + numberOfCycles; counter = 1; } recentlyused[lowerBound] = numberOfCycles; if (numberOfCycles > maxCycles) { maxCycles = numberOfCycles; } lowerBound++; } System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1)); } }

    Read the article

  • How can I get the following compiled on UVA?

    - by Michael Tsang
    Note the comment below. It cannot compiled on UVA because of a bug in GCC. #include <cstdio> #include <cstring> #include <cctype> #include <map> #include <stdexcept> class Board { public: bool read(FILE *); enum Colour {none, white, black}; Colour check() const; private: struct Index { size_t x; size_t y; Index &operator+=(const Index &) throw(std::range_error); Index operator+(const Index &) const throw(std::range_error); }; const static std::size_t size = 8; char data[size][size]; // Cannot be compiled on GCC 4.1.2 due to GCC bug 29993 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=29993 typedef bool CheckFunction(Colour, const Index &) const; CheckFunction pawn, knight, bishop, king, rook; bool queen(const Colour c, const Index &location) const { return rook(c, location) || bishop(c, location); } static char get_king(Colour c) { return c == white ? 'k' : 'K'; } template<std::size_t n> bool check_consecutive(Colour c, const Index &location, const Index (&offsets)[n]) const { for(const Index *p = offsets; p != (&offsets)[1]; ++p) { try { Index target = location + *p; for(; data[target.x][target.y] == '.'; target += *p) { } if(data[target.x][target.y] == get_king(c)) return true; } catch(std::range_error &) { } } return false; } template<std::size_t n> bool check_distinct(Colour c, const Index &location, const Index (&offsets)[n]) const { for(const Index *p = offsets; p != (&offsets)[1]; ++p) { try { Index target = location + *p; if(data[target.x][target.y] == get_king(c)) return true; } catch(std::range_error &) { } } return false; } }; int main() { Board board; for(int d = 1; board.read(stdin); ++d) { Board::Colour c = board.check(); const char *sp; switch(c) { case Board::black: sp = "white"; break; case Board::white: sp = "black"; break; case Board::none: sp = "no"; break; } std::printf("Game #%d: %s king is in check.\n", d, sp); std::getchar(); // discard empty line } } bool Board::read(FILE *f) { static const char empty[] = "........" "........" "........" "........" "........" "........" "........" "........"; // 64 dots for(char (*p)[size] = data; p != (&data)[1]; ++p) { std::fread(*p, size, 1, f); std::fgetc(f); // discard new-line } return std::memcmp(empty, data, sizeof data); } Board::Colour Board::check() const { std::map<char, CheckFunction Board::*> fp; fp['P'] = &Board::pawn; fp['N'] = &Board::knight; fp['B'] = &Board::bishop; fp['Q'] = &Board::queen; fp['K'] = &Board::king; fp['R'] = &Board::rook; for(std::size_t i = 0; i != size; ++i) { for(std::size_t j = 0; j != size; ++j) { CheckFunction Board::* p = fp[std::toupper(data[i][j])]; if(p) { Colour ret; if(std::isupper(data[i][j])) ret = white; else ret = black; if((this->*p)(ret, (Index){i, j}/* C99 extension */)) return ret; } } } return none; } bool Board::pawn(const Colour c, const Index &location) const { const std::ptrdiff_t sh = c == white ? -1 : 1; const Index offsets[] = { {sh, 1}, {sh, -1} }; return check_distinct(c, location, offsets); } bool Board::knight(const Colour c, const Index &location) const { static const Index offsets[] = { {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2} }; return check_distinct(c, location, offsets); } bool Board::bishop(const Colour c, const Index &location) const { static const Index offsets[] = { {1, 1}, {1, -1}, {-1, -1}, {-1, 1} }; return check_consecutive(c, location, offsets); } bool Board::rook(const Colour c, const Index &location) const { static const Index offsets[] = { {1, 0}, {0, -1}, {0, 1}, {-1, 0} }; return check_consecutive(c, location, offsets); } bool Board::king(const Colour c, const Index &location) const { static const Index offsets[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1} }; return check_distinct(c, location, offsets); } Board::Index &Board::Index::operator+=(const Index &rhs) throw(std::range_error) { if(x + rhs.x >= size || y + rhs.y >= size) throw std::range_error("result is larger than size"); x += rhs.x; y += rhs.y; return *this; } Board::Index Board::Index::operator+(const Index &rhs) const throw(std::range_error) { Index ret = *this; return ret += rhs; }

    Read the article

  • Runtime error on UVa Online Judge on Erdos Number

    - by 2012 - End of the World
    I am solving the Erdos number problem from the programming challenges in JAVA. The code runs perfectly in my machine. However on the online judge it results in a runtime error. Could anyone point out the mistake i made? http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=985 Here is the code import java.util.*; import java.io.*; class Main { private String inputLines[]; private String namesToBeFound[]; private String namesInEachBook[][]; private String searchItem; private boolean solnfound=false; private static final BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); static String read() throws IOException { String line; while(true) { line=br.readLine(); if(line==null) break; //eof else if(line.length()==0) continue; //blank line else { line=line.trim().replaceAll("\\s+"," "); return line; } } return null; } public static void main(String args[]) throws IOException { Main ob=new Main(); int totalPapers,calcAuthors,totalScenarios; //First input number of scenarios totalScenarios=Integer.parseInt(read()); //Now start a loop for reading total number of scenarios for(int scenario=1;scenario<=totalScenarios;scenario++) { //Now read the line containing the number of papers and authors StringTokenizer line=new StringTokenizer(read()," "); totalPapers=Integer.parseInt(line.nextToken()); calcAuthors=Integer.parseInt(line.nextToken()); //Read a line containing author names along with book names ob.inputLines=new String[totalPapers]; for(int i=0;i<totalPapers;i++) ob.inputLines[i]=read(); //Read a line containing the names to be searched ob.namesToBeFound=new String[calcAuthors]; for(int i=0;i<calcAuthors;i++) ob.namesToBeFound[i]=read(); //Now generate the array ob.buildArray(); //Now search System.out.println("Scenario "+scenario); for(int i=0;i<calcAuthors;i++) { ob.searchItem=ob.namesToBeFound[i]; if(ob.searchItem.equals("Erdos, P.")) { System.out.println("Erdos, P. 0"); continue; } ob.search(ob.namesToBeFound[i],1,new ArrayList()); if(ob.solnfound==false) System.out.println(ob.searchItem+" infinity"); ob.solnfound=false; } } } private void buildArray() { String str; namesInEachBook=new String[inputLines.length][]; for(int i=0;i<inputLines.length;i++) { str=inputLines[i]; str=str.substring(0,str.indexOf(':')); str+=","; namesInEachBook[i]=new String[(countCommas(str)+1)>>1]; for(int j=0;j<namesInEachBook[i].length;j++) { str=str.trim(); namesInEachBook[i][j]=""; namesInEachBook[i][j]+=str.substring(0,str.indexOf(','))+","; str=str.substring(str.indexOf(',')+1); namesInEachBook[i][j]+=str.substring(0,str.indexOf(',')); str=str.substring(str.indexOf(',')+1); } } } private int countCommas(String s) { int num=0; for(int i=0;i<s.length();i++) if(s.charAt(i)==',') num++; return num; } private void search(String searchElem,int ernosDepth,ArrayList searchedElem) { ArrayList searchSpace=new ArrayList(); searchedElem.add(searchElem); for(int i=0;i<namesInEachBook.length;i++) for(int j=0;j<namesInEachBook[i].length;j++) { if(namesInEachBook[i][j].equals(searchElem)) //Add all authors name in this group { for(int k=0;k<namesInEachBook[i].length;k++) { if(namesInEachBook[i][k].equals("Erdos, P.")) //Found { solnfound=true; System.out.println(searchItem+" "+ernosDepth); return; } else if(searchedElem.contains(namesInEachBook[i][k]) || searchSpace.contains(namesInEachBook[i][k])) continue; searchSpace.add(namesInEachBook[i][k]); } break; } } Iterator i=searchSpace.iterator(); while(i.hasNext()) { String cSearchElem=(String)i.next(); search(cSearchElem,ernosDepth+1,searchedElem); } } }

    Read the article

  • UVA Online Judge 3n+1 : Right answer is Wrong answer

    - by Samuraisoulification
    Ive been toying with this problem for more than a week now, I have optimized it a lot, I seem to be getting the right answer, since it's the same as when I compare it to other's answers that got accepted, but I keep getting wrong answer. Im not sure what's going on! Anyone have any advice? I think it's a problem with the input or the output, cause Im not exactly sure how this judge thing works. So if anyone could pinpoint the problem, and also give me any advice on my code, Id be very appreciative!!! #include <iostream> #include <cstdlib> #include <stdio.h> #include <vector> using namespace std; class Node{ // node for each number that has teh cycles and number private: int number; int cycles; bool cycleset; // so it knows whether to re-set the cycle public: Node(int num){ number = num; cycles = 0; cycleset = false; } int getnumber(){ return number; } int getcycles(){ return cycles; } void setnumber(int num){ number = num; } void setcycles(int num){ cycles = num; cycleset = true; } bool cycled(){ return cycleset; } }; class Cycler{ private: vector<Node> cycleArray; int biggest; int cycleReal(unsigned int number){ // actually cycles through the number int cycles = 1; if (number != 1) { if (number < 1000000) { // makes sure it's in vector bounds if (!cycleArray[number].cycled()) { // sees if it's been cycled if (number % 2 == 0) { cycles += this->cycleReal((number / 2)); } else { cycles += this->cycleReal((3 * number) + 1); } } else { // if cycled get the number of cycles and don't re-calculate, ends recursion cycles = cycleArray[number].getcycles(); } } else { // continues recursing if it's too big for the vector if (number % 2 == 0) { cycles += this->cycleReal((number / 2)); } else { cycles += this->cycleReal((3 * number) + 1); } } } if(number < 1000000){ // sets cycles table for the number in the vector if (!cycleArray[number].cycled()) { cycleArray[number].setcycles(cycles); } } return cycles; } public: Cycler(){ biggest = 0; for(int i = 0; i < 1000000; i++){ // initialize the vector, set the numbers Node temp(i); cycleArray.push_back(temp); } } int cycle(int start, int end){ // cycles thorugh the inputted numbers. int size = 0; for(int i = start; i < end ; i++){ size = this->cycleReal(i); if(size > biggest){ biggest = size; } } int temp = biggest; biggest = 0; return temp; } int getBiggest(){ return biggest; } }; int main() { Cycler testCycler; int i, j; while(cin>>i>>j){ //read in untill \n int biggest = 0; if(i > j){ biggest = testCycler.cycle(j, i); }else{ biggest = testCycler.cycle(i, j); } cout << i << " " << j << " " << biggest << endl; } return 0; }

    Read the article

  • A graph problem

    - by copperhead
    I am struggling to solve the following problem http://uva.onlinejudge.org/external/1/193.html However Im not able to get a fast solution. And as seen by the times of others, there should be a solution of maximum n^2 complexity http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problemid=129&page=problem_stats Can I get some help?

    Read the article

  • Programming Practice/Test Contest?

    - by Emmanuel
    My situation: I'm on a programming team, and this year, we want to weed out the weak link by making a competition to get the best coder from our group of candidates. Focus is on IEEExtreme-like contests. What I've done: I've been trying already for 2 weeks to get a practice or test site, like UVa or codechef. The plan after I find one: Send them (the candidates) a list of direct links to the problems (making them the "contest's problem list) get them to email me their correct answers' code at the time the judge says they have solved it and accept the fastest one into the team. Issues: We had practiced on UVa already (on programming challenges too), so our former teammate (which will be in the candidate group) already has an advantage if we used it. Codechef has all it's answers public, and since it shows the latest ones it will be extremely hard to verify if the answer was copied. And I've found other sites, like SPOJ, but they share at least some problems with codechef, making them inherit the issue of Codechef So, what alternatives do you think there are? Any site that may work? Any place to get all stuff to set up a Mooshak or similar contest (as in the stuff to get the problems, instructions to set up the server itself are easy to google)? Any other idea?

    Read the article

  • Where can you find fun/educational programming challenges?

    - by tj9991
    I've searched around for different challenge sites, and most of them seem to be geared towards difficulty in problem solving logically, rather than trying to use your language of choice to do something you haven't used it for. Their center is around mathematics rather than function design. Some kind of point system for correctly solving challenges, or solving them the most efficient/smallest would be neat as well. Listed sites Project Euler TopCoder UVa Online Judge Challenges with Python Google Code Jam Programming Challenges Less Than Dot ACM's Programing Contest archive USACO problems ITA Software's puzzle page Refactor My Code Ruby Quiz

    Read the article

  • Why I am getting Presentation Error [on hold]

    - by user105697
    Below is my code. When I submit it in UVA they are giving me Presentation error. I want to know the reason. I have tried all possible ways. In my code I use 2D-array to store each word of a sentence. I also want to know the reason for giving presentation error. #include<stdio.h> #include<string.h> int main() { char a[10000],ar[100][10000]; int i,j,k,m,n,l,len[10000],c; freopen("input.txt","r",stdin); while(gets(a)) { k=0; i=0; c=0; for(j=0; ; ++k) { if(a[k]==' ' || a[k]=='\0') { ar[i][j]='\0'; len[i]=c; if(a[k]=='\0') break; i++; j=0; c=0; } else { ar[i][j]=a[k]; c++; j++; } } for(m=0; m<=i; m++) { for(n=(len[m]-1); n>=0; n--) { printf("%c",ar[m][n]); } printf(" "); } printf("\n"); } return 0; }

    Read the article

  • webservice - unknown web method parameter name methodname

    - by ch3r1f
    I called a webservice for fetching items in fullcalendar. The method is never called and firebug gives this error: *"POST [http]://localhost:50536/FullCalendar/ServicioFullCalendar.asmx/GetEventosCalendario POST [http]://localhost:50536/FullCalendar/ServicioFullCalendar.asmx/GetEventosCalendario 500 Internal Server Error 1.01s" "unknown web method parameter name methodname"* Here is the asmx.vb code: <System.Web.Script.Services.ScriptService()> _ <System.Web.Services.WebService(Namespace:="http://localhost/uva/")> _ <System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <ToolboxItem(False)> _ Public Class ServicioFullCalendar Inherits System.Web.Services.WebService <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _ <WebMethod(MessageName:="ObtieneEventos")> _ Public Shared Function GetEventosCalendario(ByVal startDate As String, ByVal endDate As String) As String Try Return CalendarioMensualDAO.Instance.getEventos(startDate, endDate) Catch ex As Exception Throw New Exception("FullCalendar:GetEventos: " & ex.Message) Finally End Try End Function The webservice is "loaded" from the fullcalendar as follows: events: "ServicioFullCalendar.asmx/GetEventosCalendario",

    Read the article

  • What are the best programming websites on the web?

    - by lajoo
    Ok,lets have a big list here,write about the best programming websites you have approached and a description of them and they'll be added here.i'll write some websites for now: UVA Online Judge a bunch of useful programming problems are there that you could use to improve your programming. Prgrammers Heven Resources for different programming languages. SourceForge This site Has lots of open source programs available for download,it's a must-go site for a programmer. W3Schools This Websites has all you need to learn about Web-designing Languages like Java Script,Css,PHP,HTML,.... Note:This is not an advertising topic,it's just a guide for programmers to find what they need.

    Read the article

  • Need some testcases on solving this problem

    - by user285825
    I am trying to solve the minesweeper problem of acm problemset archive, http://uva,onlinejudge,org/index,php?option=com_onlinejudge&Itemid=8&category=13&page=show_problem&problem=1130 I tested with all the possible cases that I can imagine of: 1, minimum 1 1 , 1 1 # 2, maximum upto 100 upto 100 repeat until 100 3, for each position I test for mine 4 4 ,,, ,,,, ,,,, 4 4 ,#,, ,,,, ,,,, ,,,, lastly 4 4 ,,,, ,,,, ,,,, ,,,# 4, for each postion I put a ',' and surround it with mines 4 4 ,### # # # 4 4 , # # # lastly 4 4 # # # , I thought that these are reasonable and representative sets of testcases, But still Wrong answer, I am not sure what else could I test for, I would be glad if someone throw some light on further strategy to test this thing,

    Read the article

  • An alternative to reading input from Java's System.in

    - by dvanaria
    I’m working on the UVa Online Judge problem set archive as a way to practice Java, and as a way to practice data structures and algorithms in general. They give an example input file to submit to the online judge to use as a starting point (it’s the solution to problem 100). Input from the standard input stream (java.lang.System.in) is required as part of any solution on this site, but I can’t understand the implementation of reading from System.in they give in their example solution. It’s true that the input file could consist of any variation of integers, strings, etc, but every solution program requires reading basic lines of text input from System.in, one line at a time. There has to be a better (simpler and more robust) method of gathering data from the standard input stream in Java than this: public static String readLn(int maxLg) { byte lin[] = new byte[maxLg]; int lg = 0, car = -1; String line = “”; try { while (lg < maxLg) { car = System.in.read(); if ((car < 0) || (car == ‘\n’)) { break; } lin[lg++] += car; } } catch (java.io.IOException e) { return (null); } if ((car < 0) && (lg == 0)) { return (null); // eof } return (new String(lin, 0, lg)); } I’m really surprised by this. It looks like something pulled directly from K&R’s “C Programming Language” (a great book regardless), minus the access level modifer and exception handling, etc. Even though I understand the implementation, it just seems like it was written by a C programmer and bypasses most of Java’s object oriented nature. Isn’t there a better way to do this, using the StringTokenizer class or maybe using the split method of String or the java.util.regex package instead?

    Read the article

  • Graph colouring algorithm: typical scheduling problem

    - by newba
    Hi, I'm training code problems like UvA and I have this one in which I have to, given a set of n exams and k students enrolled in the exams, find whether it is possible to schedule all exams in two time slots. Input Several test cases. Each one starts with a line containing 1 < n < 200 of different examinations to be scheduled. The 2nd line has the number of cases k in which there exist at least 1 student enrolled in 2 examinations. Then, k lines will follow, each containing 2 numbers that specify the pair of examinations for each case above. (An input with n = 0 will means end of the input and is not to be processed). Output: You have to decide whether the examination plan is possible or not for 2 time slots. Example: Input: 3 3 0 1 1 2 2 0 9 8 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 Ouput: NOT POSSIBLE. POSSIBLE. I think the general approach is graph colouring, but I'm really a newb and I may confess that I had some trouble understanding the problem. Anyway, I'm trying to do it and then submit it. Could someone please help me doing some code for this problem? I will have to handle and understand this algo now in order to use it later, over and over. I prefer C or C++, but if you want, Java is fine to me ;) Thanks in advance

    Read the article

  • The Collatz Sequence problem

    - by Gandalf StormCrow
    I'm trying to solve this problem, its not a homework question, its just code I'm submitting to uva.onlinejudge.org so I can learn better java trough examples. Here is the problem sample input : 3 100 34 100 75 250 27 2147483647 101 304 101 303 -1 -1 Here is simple output : Case 1: A = 3, limit = 100, number of terms = 8 Case 2: A = 34, limit = 100, number of terms = 14 Case 3: A = 75, limit = 250, number of terms = 3 Case 4: A = 27, limit = 2147483647, number of terms = 112 Case 5: A = 101, limit = 304, number of terms = 26 Case 6: A = 101, limit = 303, number of terms = 1 The thing is this has to execute within 3sec time interval otherwise your question won't be accepted as solution, here is with what I've come up so far, its working as it should just the execution time is not within 3 seconds, here is code : import java.util.Scanner; class Main { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int start; int limit; int terms; int a = 0; while (stdin.hasNext()) { start = stdin.nextInt(); limit = stdin.nextInt(); if (start > 0) { terms = getLength(start, limit); a++; } else { break; } System.out.println("Case "+a+": A = "+start+", limit = "+limit+", number of terms = "+terms); } } public static int getLength(int x, int y) { int length = 1; while (x != 1) { if (x <= y) { if ( x % 2 == 0) { x = x / 2; length++; }else{ x = x * 3 + 1; length++; } } else { length--; break; } } return length; } } And yes here is how its meant to be solved : An algorithm given by Lothar Collatz produces sequences of integers, and is described as follows: Step 1: Choose an arbitrary positive integer A as the first item in the sequence. Step 2: If A = 1 then stop. Step 3: If A is even, then replace A by A / 2 and go to step 2. Step 4: If A is odd, then replace A by 3 * A + 1 and go to step 2. And yes my question is how can I make it work inside 3 seconds time interval?

    Read the article

  • The Skyline Problem.

    - by zeroDivisible
    I just came across this little problem on UVA's Online Judge and thought, that it may be a good candidate for a little code-golf. The problem: You are to design a program to assist an architect in drawing the skyline of a city given the locations of the buildings in the city. To make the problem tractable, all buildings are rectangular in shape and they share a common bottom (the city they are built in is very flat). The city is also viewed as two-dimensional. A building is specified by an ordered triple (Li, Hi, Ri) where Li and Ri are left and right coordinates, respectively, of building i and Hi is the height of the building. In the diagram below buildings are shown on the left with triples (1,11,5), (2,6,7), (3,13,9), (12,7,16), (14,3,25), (19,18,22), (23,13,29), (24,4,28) and the skyline, shown on the right, is represented by the sequence: 1, 11, 3, 13, 9, 0, 12, 7, 16, 3, 19, 18, 22, 3, 23, 13, 29, 0 The output should consist of the vector that describes the skyline as shown in the example above. In the skyline vector (v1, v2, v3, ... vn) , the vi such that i is an even number represent a horizontal line (height). The vi such that i is an odd number represent a vertical line (x-coordinate). The skyline vector should represent the "path" taken, for example, by a bug starting at the minimum x-coordinate and traveling horizontally and vertically over all the lines that define the skyline. Thus the last entry in the skyline vector will be a 0. The coordinates must be separated by a blank space. If I will not count declaration of provided (test) buildings and including all spaces and tab characters, my solution, in Python, is 223 characters long. Here is the condensed version: B=[[1,11,5],[2,6,7],[3,13,9],[12,7,16],[14,3,25],[19,18,22],[23,13,29],[24,4,28]] # Solution. R=range v=[0 for e in R(max([y[2] for y in B])+1)] for b in B: for x in R(b[0], b[2]): if b[1]>v[x]: v[x]=b[1] p=1 k=0 for x in R(len(v)): V=v[x] if p and V==0: continue elif V!=k: p=0 print "%s %s" % (str(x), str(V)), k=V I think that I didn't made any mistake but if so - feel free to criticize me. EDIT I don't have much reputation, so I will pay only 100 for a bounty - I am curious, if anyone could try to solve this in less than .. lets say, 80 characters. Solution posted by cobbal is 101 characters long and currently it is the best one. ANOTHER EDIT I thought, that 80 characters is a sick limit for this kind of problem. cobbal, with his 46 character solution totaly amazed me - though I must admit, that I spent some time reading his explanation before I partially understood what he had written.

    Read the article

  • why is my 3n+1 problem solution wrong?

    - by nunos
    I have recently started reading "Programming Challenges" book by S. Skiena and believe or not I am kind of stuck in the very first problem. Here's a link to the problem: 3n+1 problem Here's my code: #include <iostream> #include <vector> #include <algorithm> using namespace std; unsigned long calc(unsigned long n); int main() { int i, j, a, b, m; vector<int> temp; while (true) { cin >> i >> j; if (cin.fail()) break; if (i < j) { a = i; b = j; } else { a = j; b = i; } temp.clear(); for (unsigned int k = a; k != b; k++) { temp.push_back(calc(k)); } m = *max_element(temp.begin(), temp.end()); cout << i << ' ' << j << ' ' << m << endl; } } unsigned long calc(unsigned long n) { unsigned long ret = 1; while (n != 1) { if (n % 2 == 0) n = n/2; else n = 3*n + 1; ret++; } return ret; } I know the code is inefficient and I should not be using vectors to store the data. Anyway, I still would like to know what it's wrong with this, since, for me, it makes perfect sense, even though I am getting WA (wrong answer at programming challenges judge and RE (Runtime Error) at UVa judge). Thanks.

    Read the article

1