-
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.
Time: 399 ms (89.81%), Space: 155.6 MB (94.17%) - LeetHub
- Loading branch information
1 parent
37c3ed6
commit ecd522c
Showing
1 changed file
with
26 additions
and
23 deletions.
There are no files selected for viewing
49 changes: 26 additions & 23 deletions
49
...th-different-adjacent-characters/2246-longest-path-with-different-adjacent-characters.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 |
---|---|---|
@@ -1,29 +1,32 @@ | ||
class Solution { | ||
public: | ||
int dfs(vector<vector<int>>& x,int& mx,int i,string& s){ | ||
if(x[i].size()==0) return 1; | ||
vector<int> e; | ||
int mx1=0,mx2=0; | ||
for(int j=0;j<x[i].size();j++){ | ||
int a = dfs(x,mx,x[i][j],s); | ||
if(s[x[i][j]]==s[i]) a=0; | ||
if(a>mx1){ | ||
mx2=mx1; | ||
mx1=a; | ||
} | ||
else if(a>mx2) mx2=a; | ||
} | ||
mx=max(mx,mx1+mx2+1); | ||
return mx1+1; | ||
|
||
int maxi2=0; | ||
int solve(string &s,vector<vector<int>> &adj,int k) | ||
{ | ||
int maxi=0; | ||
int ans=0; | ||
for(int i=0;i<adj[k].size();i++) | ||
{ | ||
|
||
ans=1+solve(s,adj,adj[k][i]); | ||
if(s[k]!=s[adj[k][i]]) | ||
{ | ||
if(maxi2< maxi+ans)maxi2=maxi+ans; | ||
maxi=max(maxi,ans); | ||
|
||
} | ||
ans=0; | ||
} | ||
return maxi; | ||
} | ||
|
||
int longestPath(vector<int>& par, string s) { | ||
int n=par.size(),mx=1; | ||
vector<vector<int>> x(n,vector<int>()); | ||
for(int i=0;i<n;i++){ | ||
if(par[i]!=-1) x[par[i]].push_back(i); | ||
int longestPath(vector<int>& parent, string s) { | ||
vector<vector<int>> adj(parent.size()); | ||
for(int i=1;i<parent.size();i++) | ||
{ | ||
adj[parent[i]].push_back(i); | ||
} | ||
dfs(x,mx,0,s); | ||
return mx; | ||
solve(s,adj,0); | ||
return maxi2+1; | ||
} | ||
}; |