-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathDay-072.cpp
79 lines (76 loc) · 2.38 KB
/
Day-072.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <bits/stdc++.h>
using namespace std;
class InfinitePathException:std::exception{
public:
const char* what() const throw(){
return "Detected Cycle, No Answer Possible";
}
};
class Solution{
private:
map<char,int>freqCounter;
set<int>visited;
map<int , vector<int>>graph;
int maxPathValue;
void createGraph(vector<vector<int>>&edges){
for(auto&edge:edges){
auto&& source = edge[0];
auto&& destination = edge[1];
graph[ source ].push_back(destination);
}
}
void dfs(const string&pathCharacters , int currentNode){
freqCounter[ pathCharacters[currentNode] ]++;
visited.insert(currentNode);
for(auto&itr:graph[currentNode]){
if(visited.count(itr)){
throw InfinitePathException();
}else{
dfs(pathCharacters , itr);
}
}
maxPathValue = std::max(maxPathValue , freqCounter[ pathCharacters[ currentNode ] ]);
visited.erase(currentNode);
freqCounter[ pathCharacters[currentNode] ]--;
}
public:
int getMaxValuePath(const string &pathCharacters , vector<vector<int>>&edge){
maxPathValue = numeric_limits<int>::min();
createGraph(edge);
for(auto&itr:graph){ // we need to check dfs from each node as there can be situation like A(1)->A(0)->A(2)->A(3)
try{
dfs(pathCharacters , itr.first);
}catch(...){
throw;
}
}
if(maxPathValue == numeric_limits<int>::min()){
assert(false);
}else{
return maxPathValue;
}
}
};
int main(void){
string s = "ABACA";
vector<vector<int>>edges1;
edges1.push_back({0,1});
edges1.push_back({0,2});
edges1.push_back({2,3});
edges1.push_back({3,4});
Solution s1;
try{
cout<<s1.getMaxValuePath(s , edges1)<<'\n';
}catch(InfinitePathException&e){
cout<<e.what()<<'\n';
}
vector<vector<int>>edges2;
s = "A";
edges2.push_back({0,0});
try{
cout<<s1.getMaxValuePath(s , edges2)<<'\n';
}catch(InfinitePathException&e){
cout<<e.what()<<'\n';
}
return 0;
}