File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ #include " ../Header.h"
2+
3+ using namespace std ;
4+ int numSquares (int n) {
5+ bool *isVisited = new bool [n+1 ];
6+ memset (isVisited, 0 , n+1 );
7+ vector<int > squares;
8+ queue<int > BFS;
9+ for (int i = 1 ; i*i <= n; i++) {
10+ int t = i*i;
11+ if (t == n) return 1 ;
12+ squares.push_back (t);
13+ BFS.push (t);
14+ isVisited[t] = 1 ;
15+ }
16+ int curLevelCnt = 0 , curLevel = 1 , preLevelCnt = squares.size ();
17+
18+ while (1 ) {
19+ curLevel++;
20+ while (preLevelCnt--) {
21+ int num = BFS.front ();
22+ BFS.pop ();
23+ for (auto square: squares) {
24+ int t = num + square;
25+ if (t == n) return curLevel;
26+ if (t > n) break ;
27+ if (!isVisited[t]) {
28+ curLevelCnt++;
29+ isVisited[t] = 1 ;
30+ BFS.push (t);
31+ }
32+
33+ }
34+ }
35+ preLevelCnt = curLevelCnt;
36+ }
37+ }
38+ int main (int argc, char const *argv[])
39+ {
40+ srand ((int )time (NULL ));
41+ int num = random (9999 );
42+ cout << num << " " << numSquares (num) << endl;
43+ return 0 ;
44+ }
You can’t perform that action at this time.
0 commit comments