// Question 2(c): Minimized DFA
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
struct State {
int id;
std::map<char, int> transitions; // symbol -> state ID
bool isAccept;
};
int main() {
// Assume the DFA from part (b) has states 0 to N with transitions defined
// For demonstration, we'll define a simple DFA manually
// Example DFA
std::vector<State> dfa = {
{0, { {'a', 1}, {'b', 0} }, false},
{1, { {'a', 2}, {'b', 0} }, false},
{2, { {'a', 2}, {'b', 3} }, true},
{3, { {'a', 1}, {'b', 0} }, false}
};
int numStates = dfa.size();
// Initialize partitions: accepting and non-accepting
std::set<int> accept;
std::set<int> nonAccept;
for(int i = 0; i < numStates; ++i) {
if(dfa[i].isAccept)
accept.insert(i);
else
nonAccept.insert(i);
}
std::vector< std::set<int> > partitions;
if(!accept.empty()) partitions.push_back(accept);
if(!nonAccept.empty()) partitions.push_back(nonAccept);
bool updated = true;
while(updated) {
updated = false;
std::vector< std::set<int> > newPartitions;
for(auto &group : partitions) {
// Attempt to split group
std::map<std::vector<int>, std::set<int>> splitter;
for(auto state : group) {
std::vector<int> key;
for(auto &[sym, target] : dfa[state].transitions) {
// Find which partition the target is in
int part = -1;
for(int p = 0; p < partitions.size(); ++p) {
if(partitions[p].find(target) != partitions[p].end()) {
part = p;
break;
}
}
key.push_back(part);
}
splitter[key].insert(state);
}
if(splitter.size() > 1) {
updated = true;
for(auto &[k, s] : splitter)
newPartitions.push_back(s);
}
else {
newPartitions.push_back(group);
}
}
partitions = newPartitions;
}
// Mapping old states to new states
std::map<int, int> stateMapping;
for(int i = 0; i < partitions.size(); ++i) {
for(auto state : partitions[i]) {
stateMapping[state] = i;
}
}
// Building minimized DFA
std::vector<State> minDFA(partitions.size(), State());
for(int i = 0; i < partitions.size(); ++i) {
// Set isAccept
minDFA[i].isAccept = dfa[*partitions[i].begin()].isAccept;
for(auto &[sym, target] : dfa[*partitions[i].begin()].transitions) {
minDFA[i].transitions[sym] = stateMapping[target];
}
}
// Display Minimized DFA transitions
for(int i = 0; i < minDFA.size(); ++i) {
std::cout << "D" << i;
if(minDFA[i].isAccept) std::cout << " (Accept)";
std::cout << "\n";
for(auto &[sym, target] : minDFA[i].transitions) {
std::cout << " --" << sym << "--> D" << target << "\n";
}
}
std::cout << "DFA minimized.\n";
return 0;
}