forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 2305.Fair-Distribution-of-Cookies_v2.cpp
- Loading branch information
1 parent
82c00f4
commit ca84944
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v2.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
class Solution { | ||
int plan[8]; | ||
public: | ||
int distributeCookies(vector<int>& cookies, int k) | ||
{ | ||
sort(cookies.rbegin(), cookies.rend()); | ||
|
||
int left = 1, right = INT_MAX; | ||
while (left < right) | ||
{ | ||
for (int i=0; i<k; i++) | ||
plan[i] = 0; | ||
|
||
int mid = left+(right-left)/2; | ||
if (dfs(cookies, mid, k, 0)) | ||
right = mid; | ||
else | ||
left = mid+1; | ||
} | ||
return left; | ||
} | ||
|
||
bool dfs(vector<int>& cookies, int limit, int k, int idx) | ||
{ | ||
if (idx == cookies.size()) return true; | ||
|
||
int flag = 0; | ||
for (int i=0; i<k; i++) | ||
{ | ||
if (plan[i]+cookies[idx] > limit) continue; | ||
if (plan[i]==0) | ||
{ | ||
if (flag==1) continue; | ||
flag = 1; | ||
} | ||
|
||
plan[i] += cookies[idx]; | ||
if (dfs(cookies, limit, k, idx+1)) | ||
return true; | ||
plan[i] -= cookies[idx]; | ||
} | ||
return false; | ||
} | ||
}; |