2012-02-27 14:03:06Morris

[UVA] 11407 - Squares

  Squares 

For any positive integer N , N = a1$scriptstyle wedge$2 + a2$scriptstyle wedge$2 +...+ an$scriptstyle wedge$2 that is, any positive integer can be represented as sum of squares of other numbers.

Your task is to print the smallest `n ' such that N = a1$scriptstyle wedge$2 + a2$scriptstyle wedge$2 +...+ an$scriptstyle wedge$2 .

Input 

The first line of the input will contain an integer `t ' which indicates the number of test cases to follow.

Each test case will contain a single integer `N ' (1$ le$N$ le$10000) on a line by itself.

Output 

Print an integer which represents the smallest `n ' such that

N = a1$scriptstyle wedge$2 + a2$scriptstyle wedge$2 +...+ an$scriptstyle wedge$2 .


Explanation for sample test cases:


5 - > number of test cases

1 = 1$scriptstyle wedge$2 (1 term)

2 = 1$scriptstyle wedge$2 + 1$scriptstyle wedge$2 (2 terms)

3 = 1$scriptstyle wedge$2 + 1$scriptstyle wedge$2 + 1$scriptstyle wedge$2 (3 terms)

1 = 2$scriptstyle wedge$2 (1 term)

2 = 5$scriptstyle wedge$2 + 5$scriptstyle wedge$2 (2 terms)

Sample Input 

5
1
2
3
4
50

Sample Output 

1
2
3
1
2


做法 : 類同零錢問題

#include <stdio.h>
#define oo 10000
int main() {
int t, N, i, j;
scanf("%d", &t);
long long DP[10001] = {};
DP[0] = 0;
for(i = 1; i <= 10000; i++) DP[i] = oo;
for(i = 1; i <= 100; i++) {
for(j = i*i; j <= 10000; j++)
DP[j] = DP[j] < DP[j-i*i]+1 ? DP[j] : DP[j-i*i]+1;
}
while(t--) {
scanf("%d", &N);
printf("%lld\n", DP[N]);
}
return 0;
}