#include #include #include #include #include #include using namespace std; #define all(c) (c).begin(), (c).end() #define rall(c) (c).rbegin(), (c).rend() #define _auto(var, x) typeof(x) var = (x) #define _auxforeach(it, b, e) for(_auto(it, b), _itend = e; it != _itend; ++it) #define foreach(it, r...) _auxforeach(it, r) typedef long long LLONG; typedef pair PII; typedef vector VI; typedef vector VVI; typedef vector VB; typedef vector VVB; enum { INF = 1<<30 }; struct EulerianCycle { // (Closed Tour) // (OutDegree - InDegree) must be 0 for all vertices. VVI mtx; // input (manipulated) const int V; // input VI nextAdj; // private VVI answer; // output (list of stacks to be popped) /// mtx = binary adjacency matrix (directed graph) EulerianCycle(const VVI& mtx) : mtx(mtx), V(mtx.size()), nextAdj(V,0), answer(V) { // O(Vē) foreach(i, 0,V) adjustNext(i); int nd = 0; while(nd < V) { if(nextAdj[nd] < V) depthFirstSearch(nd); else nd ++; } } /// Stores nodes from cycle in "output". void visit(VI& output) { // O(E) VVI stackOf = answer; int nd = 0; while(stackOf[nd].empty() and nd < V) nd++; if(nd == V) return; output.push_back(nd); while(!stackOf[nd].empty()) { int newNd = stackOf[nd].back(); output.push_back(newNd); stackOf[nd].pop_back(); nd = newNd; } } /// Stores nodes from cycle in "output". Starts at "firstNode". void visit(VI& output, int firstNode) { // O(E) visit(output); if(output.empty()) return; // All nodes "neighborless"... output.pop_back(); VI::iterator it = find(all(output), firstNode); if(it == output.end()) throw "Node has no neighbors!"; rotate(output.begin(), it, output.end()); output.push_back(output[0]); } void adjustNext(int nd) { // O(V) int& next = nextAdj[nd]; while(next < V and mtx[nd][next] == 0) next++; } void depthFirstSearch(int firstNd) { int nd = firstNd; bool first = true; while(nd != firstNd or first) { int adj = nextAdj[nd]; if(adj == V) throw "No Eulerian Cycle!"; answer[nd].push_back(adj); mtx[nd][adj] --; adjustNext(nd); nd = adj; first = false; } } }; #define bit(n, i) ((n & (1<0?1:0) #define upbit(n, i) (n |= (1<B) onde os dois ultimos bits de A\nsao iguais aos dois primeiros bits de B...\n"); for(int i=0; i drum; puts("O Drum e':"); for(int i=0; i