-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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_v3.cpp
- Loading branch information
1 parent
f9d6452
commit fea9223
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v3.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,52 @@ | ||
class Solution { | ||
int plan[8]; | ||
public: | ||
int distributeCookies(vector<int>& cookies, int k) | ||
{ | ||
sort(cookies.rbegin(), cookies.rend()); | ||
int n = cookies.size(); | ||
|
||
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, (1<<n)-1)) | ||
right = mid; | ||
else | ||
left = mid+1; | ||
} | ||
return left; | ||
} | ||
|
||
bool dfs(vector<int>& cookies, int limit, int k, int curPerson, int state) | ||
{ | ||
if (curPerson == k) | ||
{ | ||
return state == 0; | ||
} | ||
|
||
for (int subset=state; subset>0; subset=(subset-1)&state) | ||
{ | ||
int sum = getSum(cookies, subset); | ||
if (sum > limit) continue; | ||
if (dfs(cookies, limit, k, curPerson+1, state-subset)) | ||
return true; | ||
}; | ||
|
||
return false; | ||
} | ||
|
||
int getSum(vector<int>& cookies, int state) | ||
{ | ||
int ret = 0; | ||
for (int i=0; i<cookies.size(); i++) | ||
{ | ||
if ((state>>i)&1) | ||
ret += cookies[i]; | ||
} | ||
return ret; | ||
} | ||
}; |