Skip to content
/ leetcode Public
  • Sponsor doocs/leetcode

  • Notifications You must be signed in to change notification settings
  • Fork 9.1k

3500 3599 / 3530. Maximum Profit from Valid Topological Order in DAG #4397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions solution/0700-0799/0770.Basic Calculator IV/solutions.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <bits/stdc++.h>
using namespace std;
struct Poly{
map<vector<string>, long> d;
Poly(long v=0){ if(v) d[{}]=v; }
Poly(const string &s){ d[{s}]=1; }
};
Poly add(const Poly &a,const Poly &b){ Poly r=a; for(auto &p:b.d) r.d[p.first]+=p.second; for(auto it=r.d.begin();it!=r.d.end();){ if(it->second==0) r.d.erase(it++); else ++it;} return r; }
Poly sub(const Poly &a,const Poly &b){ Poly r=a; for(auto &p:b.d) r.d[p.first]-=p.second; for(auto it=r.d.begin();it!=r.d.end();){ if(it->second==0) r.d.erase(it++); else ++it;} return r; }
Poly mul(const Poly &a,const Poly &b){ Poly r; for(auto &p:a.d) for(auto &q:b.d){ auto v=p.first; v.insert(v.end(),q.first.begin(),q.first.end()); sort(v.begin(),v.end()); r.d[v]+=p.second*q.second; } for(auto it=r.d.begin();it!=r.d.end();){ if(it->second==0) r.d.erase(it++); else ++it;} return r; }
class Solution {
public:
vector<string> basicCalculatorIV(string expr, vector<string>& evv, vector<int>& evi){
unordered_map<string,long> mp;
for(int i=0;i<evv.size();i++) mp[evv[i]] = evi[i];
vector<string> toks;
string t;
for(char c:expr){
if(c==' '){ if(!t.empty()){ toks.push_back(t); t.clear(); }}
else if(strchr("()+-*",c)){
if(!t.empty()){ toks.push_back(t); t.clear(); }
toks.push_back(string(1,c));
} else t.push_back(c);
}
if(!t.empty()) toks.push_back(t);
int i=0;
function<Poly()> parseE, parseT, parseP;
parseP = [&]{ string s=toks[i++]; if(s=="("){ Poly r = parseE(); i++; return r;} if(isdigit(s[0])) return Poly(stol(s)); return mp.count(s)? Poly(mp[s]) : Poly(s); };
parseT = [&]{ Poly r=parseP(); while(i<toks.size() && toks[i]=="*"){ i++; r = mul(r, parseP()); } return r; };
parseE = [&]{ Poly r=parseT(); while(i<toks.size()&&(toks[i]=="+"||toks[i]=="-")){ string op=toks[i++]; Poly p=parseT(); r = (op=="+"? add(r,p) : sub(r,p)); } return r; };
Poly res = parseE();
vector<pair<vector<string>,long>> v(res.d.begin(), res.d.end());
sort(v.begin(), v.end(), [](auto &a, auto &b){ if(a.first.size()!=b.first.size()) return a.first.size()>b.first.size(); return a.first<b.first; });
vector<string> ans;
for(auto &p:v) if(p.second){
string s = to_string(p.second);
for(auto &var:p.first) s += "*" + var;
ans.push_back(s);
}
return ans;
}
};
59 changes: 59 additions & 0 deletions solution/1500-1599/1591.Strange Printer II/Solutions.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
class Solution {
public:
bool isPrintable(vector<vector<int>>& targetGrid) {
int m = targetGrid.size(), n = targetGrid[0].size();

const int MAXC = 60;
vector<bool> seen(MAXC+1,false);
vector<int> minR(MAXC+1, m), maxR(MAXC+1, -1);
vector<int> minC(MAXC+1, n), maxC(MAXC+1, -1);

for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int c = targetGrid[i][j];
seen[c] = true;
minR[c] = min(minR[c], i);
maxR[c] = max(maxR[c], i);
minC[c] = min(minC[c], j);
maxC[c] = max(maxC[c], j);
}
}

vector<bitset<MAXC+1>> adj(MAXC+1);
vector<int> indeg(MAXC+1,0);
for(int c=1;c<=MAXC;c++){
if(!seen[c]) continue;
for(int i=minR[c]; i<=maxR[c]; i++){
for(int j=minC[c]; j<=maxC[c]; j++){
int d = targetGrid[i][j];
if(d!=c && !adj[c].test(d)){
adj[c].set(d);
indeg[d]++;
}
}
}
}

// Kahn's algorithm on at most 60 nodes
queue<int> q;
int totalColors = 0;
for(int c=1;c<=MAXC;c++){
if(!seen[c]) continue;
totalColors++;
if(indeg[c]==0) q.push(c);
}

int seenCount = 0;
while(!q.empty()){
int u = q.front(); q.pop();
seenCount++;
for(int v=1;v<=MAXC;v++){
if(adj[u].test(v) && --indeg[v]==0){
q.push(v);
}
}
}

return seenCount == totalColors;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <array>
#include <climits>
#include <queue>
#include <vector>
using namespace std;

class Solution {
public:
int secondMinimum(int n, vector<vector<int>>& edges, int time, int change) {
vector<vector<int>> adj(n + 1);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
vector<array<int, 2>> dist(n + 1, {INT_MAX, INT_MAX});
queue<pair<int, int>> q;
dist[1][0] = 0;
q.emplace(1, 0);

while (!q.empty()) {
auto [u, t] = q.front();
q.pop();
for (int v : adj[u]) {
int cycles = t / change;
int wait = (cycles % 2 == 1 ? change - (t % change) : 0);
int t2 = t + wait + time;
if (t2 < dist[v][0]) {
dist[v][1] = dist[v][0];
dist[v][0] = t2;
q.emplace(v, t2);
} else if (t2 > dist[v][0] && t2 < dist[v][1]) {
dist[v][1] = t2;
q.emplace(v, t2);
}
}
}

return dist[n][1];
}
};
48 changes: 48 additions & 0 deletions solution/2000-2099/2097.Valid Arrangement of Pairs/Solutions.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <vector>
#include <unordered_map>
#include <stack>
using namespace std;

class Solution {
public:
vector<vector<int>> validArrangement(vector<vector<int>>& pairs) {
unordered_map<int, stack<int>> graph;
unordered_map<int, int> out_degree;

for (auto& p : pairs) {
graph[p[0]].push(p[1]);
out_degree[p[0]]++;
out_degree[p[1]]--;
}

int start = pairs[0][0];
for (auto& [node, degree] : out_degree) {
if (degree > 0) {
start = node;
break;
}
}

vector<vector<int>> result;
stack<int> path;
path.push(start);

while (!path.empty()) {
int current = path.top();
if (!graph[current].empty()) {
path.push(graph[current].top());
graph[current].pop();
} else {
if (path.size() > 1) {
int end = path.top(); path.pop();
result.push_back({path.top(), end});
} else {
path.pop();
}
}
}

reverse(result.begin(), result.end());
return result;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <functional>
using namespace std;

class Solution
{
public:
vector<vector<int>> supersequences(vector<string> &words)
{
const int ALPHA = 26;
bool used[ALPHA] = {};
for (auto &w : words)
for (char c : w)
used[c - 'a'] = true;

vector<int> charMap(ALPHA, -1);
vector<char> chars;
int charCount = 0;
for (int c = 0; c < ALPHA; c++)
{
if (used[c])
{
charMap[c] = charCount++;
chars.push_back('a' + c);
}
}

vector<vector<bool>> graph(charCount, vector<bool>(charCount));
vector<bool> selfLoop(charCount);
for (auto &w : words)
{
int u = charMap[w[0] - 'a'], v = charMap[w[1] - 'a'];
if (u == v)
selfLoop[u] = true;
else
graph[u][v] = true;
}

vector<int> disc(charCount, -1), low(charCount), comp(charCount, -1);
vector<bool> inStack(charCount);
stack<int> stk;
int time = 0, sccTotal = 0;

function<void(int)> tarjan = [&](int u)
{
disc[u] = low[u] = time++;
stk.push(u);
inStack[u] = true;

for (int v = 0; v < charCount; v++)
{
if (!graph[u][v])
continue;
if (disc[v] == -1)
{
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if (inStack[v])
{
low[u] = min(low[u], disc[v]);
}
}

if (low[u] == disc[u])
{
while (true)
{
int v = stk.top();
stk.pop();
inStack[v] = false;
comp[v] = sccTotal;
if (v == u)
break;
}
sccTotal++;
}
};

for (int i = 0; i < charCount; i++)
if (disc[i] == -1)
tarjan(i);

vector<vector<int>> sccGroups(sccTotal);
for (int i = 0; i < charCount; i++)
sccGroups[comp[i]].push_back(i);

vector<vector<int>> sccGraph(sccTotal);
vector<int> inDegree(sccTotal);
for (int u = 0; u < charCount; u++)
{
for (int v = 0; v < charCount; v++)
{
if (graph[u][v] && comp[u] != comp[v])
{
sccGraph[comp[u]].push_back(comp[v]);
inDegree[comp[v]]++;
}
}
}

queue<int> q;
vector<int> topoOrder;
for (int i = 0; i < sccTotal; i++)
if (inDegree[i] == 0)
q.push(i);

while (!q.empty())
{
int u = q.front();
q.pop();
topoOrder.push_back(u);
for (int v : sccGraph[u])
{
if (--inDegree[v] == 0)
q.push(v);
}
}

auto isAcyclic = [](const vector<vector<bool>> &g, int mask, int n)
{
vector<bool> removed(n);
for (int i = 0; i < n; i++)
if (mask & (1 << i))
removed[i] = true;

vector<int> deg(n);
for (int u = 0; u < n; u++)
{
if (removed[u])
continue;
for (int v = 0; v < n; v++)
{
if (!removed[v] && g[u][v])
deg[v]++;
}
}

queue<int> q;
int cnt = 0;
int total = n - __builtin_popcount(mask);
for (int i = 0; i < n; i++)
if (!removed[i] && deg[i] == 0)
q.push(i);

while (!q.empty())
{
int u = q.front();
q.pop();
cnt++;
for (int v = 0; v < n; v++)
{
if (!removed[v] && g[u][v] && --deg[v] == 0)
q.push(v);
}
}
return cnt == total;
};

auto findMinFVS = [&](const vector<vector<bool>> &g, int n)
{
set<vector<int>> patterns;
for (int sz = 0; sz <= n; sz++)
{
bool found = false;
for (int mask = 0; mask < (1 << n); mask++)
{
if (__builtin_popcount(mask) != sz)
continue;
if (isAcyclic(g, mask, n))
{
vector<int> freq(n, 1);
for (int i = 0; i < n; i++)
if (mask & (1 << i))
freq[i] = 2;
patterns.insert(freq);
found = true;
}
}
if (found)
break;
}
return vector<vector<int>>(patterns.begin(), patterns.end());
};

vector<vector<vector<int>>> sccPatterns(sccTotal);
for (int i = 0; i < sccTotal; i++)
{
auto &group = sccGroups[i];
if (group.size() == 1)
{
sccPatterns[i] = selfLoop[group[0]] ? vector<vector<int>>{{2}} : vector<vector<int>>{{1}};
continue;
}

vector<vector<bool>> subgraph(group.size(), vector<bool>(group.size()));
vector<int> localToGlobal(group.size());
for (int j = 0; j < group.size(); j++)
{
localToGlobal[j] = group[j];
if (selfLoop[group[j]])
subgraph[j][j] = true;
for (int k = 0; k < group.size(); k++)
{
if (graph[group[j]][group[k]])
subgraph[j][k] = true;
}
}
sccPatterns[i] = findMinFVS(subgraph, group.size());
}

vector<vector<int>> result = {{}};
for (int scc : topoOrder)
{
vector<vector<int>> newResult;
for (auto &freq : result)
{
for (auto &pattern : sccPatterns[scc])
{
vector<int> newFreq = freq;
newFreq.resize(charCount);
for (int i = 0; i < sccGroups[scc].size(); i++)
{
int globalIdx = sccGroups[scc][i];
newFreq[globalIdx] = pattern[i];
}
newResult.push_back(newFreq);
}
}
result = move(newResult);
}

set<vector<int>> uniqueFreqs;
for (auto &freq : result)
{
vector<int> finalFreq(ALPHA);
for (int i = 0; i < charCount; i++)
finalFreq[chars[i] - 'a'] = freq[i];
uniqueFreqs.insert(finalFreq);
}

return vector<vector<int>>(uniqueFreqs.begin(), uniqueFreqs.end());
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
public:
int maxProfit(int n, vector<vector<int>>& edges, vector<int>& score) {
vector<int> prereq(n, 0);
for (auto &e : edges) {
int u = e[0], v = e[1];
prereq[v] |= (1 << u);
}

int N = 1 << n;
vector<int> dp(N, INT_MIN);
dp[0] = 0;

for (int mask = 0; mask < N; ++mask) {
if (dp[mask] < 0) continue;
int pos = __builtin_popcount(mask) + 1;
int free = (~mask) & (N - 1);
for (int i = 0; i < n; ++i) {
if ((free & (1 << i))
&& (mask & prereq[i]) == prereq[i]) {
int m2 = mask | (1 << i);
dp[m2] = max(dp[m2], dp[mask] + score[i] * pos);
}
}
}

return dp[N - 1];
}
};