-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 2601. Prime Subtraction Operation
- Loading branch information
1 parent
780e8aa
commit f68ee5e
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
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,36 @@ | ||
const int N = 1000; | ||
vector<int> lp(N + 1); | ||
vector<int> pr; | ||
|
||
void linearSieve() { | ||
for (int i = 2; i <= N; ++i) { | ||
if (lp[i] == 0) { | ||
lp[i] = i; | ||
pr.push_back(i); | ||
} | ||
for (int j = 0; i * pr[j] <= N; ++j) { | ||
lp[i * pr[j]] = pr[j]; | ||
if (pr[j] == lp[i]) { | ||
break; | ||
} | ||
} | ||
} | ||
} | ||
|
||
class Solution { | ||
public: | ||
bool primeSubOperation(vector<int>& nums) { | ||
int n = nums.size(); | ||
if (n == 1) return true; | ||
linearSieve(); | ||
for (int i = n - 2; i >= 0; --i) { | ||
if (nums[i] >= nums[i + 1]) { | ||
int target = nums[i] - nums[i + 1] + 1; | ||
auto it = lower_bound(pr.begin(), pr.end(), target); | ||
if (it == pr.end() || *it >= nums[i]) return false; | ||
nums[i] -= *it; | ||
} | ||
} | ||
return true; | ||
} | ||
}; |