UVa : 11342 (Three-Square)



// http://uva.onlinejudge.org/external/113/11342.html

// @BEGIN_OF_SOURCE_CODE

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#define INT_MAX 2147483647
#define INT_MIN -2147483647
#define pi acos(-1.0)
#define N 1000000
#define LL unsigned long long
using namespace std;

struct square {
    int sq;
    int a;
    int b;
} s [50000];

bool isPerfectSquare (int p)
{
    int sqr = sqrt (p);

    if ( sqr * sqr == p ) return true;
    return false;
}

int main ()
{
    int testCase;
    scanf ("%d", &testCase);

    int len_s = 0;

    for ( int i = 0; i < 225; i++ ) {
        for ( int j = i; j < 225; j++ ) {
            s [len_s].sq = i * i + j * j;
            s [len_s].a = i;
            s [len_s].b = j;
            len_s++;
        }
    }

    while ( testCase-- ) {
        int k;
        scanf ("%d", &k);

        //printf ("%d\n", len_s);

        bool printed = false;

        for ( int i = 0; i < len_s; i++ ) {
            if ( isPerfectSquare (k - s [i].sq) ) {
                int output [3];
                output [0] = s [i].a;
                output [1] = s [i].b;
                output [2] = (int) sqrt (k - s [i].sq);
                sort (output, output + 3);
                printf ("%d %d %d\n", output [0], output [1], output [2]);
                printed = true;
                break;
            }
        }

        if ( !printed ) printf ("-1\n");

    }

	return 0;
}

// @END_OF_SOURCE_CODE

2 thoughts on “UVa : 11342 (Three-Square)

  1. you can do it simply like this:

    #include 
    #include 
    #include 
    using namespace std;
    
    int main() {
    	int i, test, n, idx[3], sq[256];
    	for(i = 1; i = 0 && n; i--) {
    			idx[i] = (upper_bound(sq, sq + 128, n)-sq)-1;
    			n -= sq[idx[i]];
    		}
    		if(!n) printf("%d %d %d\n", idx[0], idx[1], idx[2]);
    		else printf("-1\n");
    	}
    	return 0;
    }
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s