/** if there are M non-intersecting Euler Circuit,and the row's size is N,we have the answer N/2-M;
*
* ****explanation:
* for example ,if the Row is { 5,4,2,6,3,1,0,7 };
* the one Euler Circuit is {5,4},because 5->4 and 4->5,they are a Euler Circuit ;
* the other Euler Circuit is {2,6,3,1,0,7}; beacause (2,6)->(3,1)->(0,7)->(2,6); we set the 2 initial value,then we need 3,so we get (2,6)->(3,1),and then the 1 need 0;so we get (2,6)->(3,1)->(0,7),the 7 need 6,we get (2,6)->(3,1)->(0,7)->(2,6),but We have already visited (2,6). so we get another Euler Circuit.
* now we have already visited all num in Row,there are two Euler Circuit .so the answer is 8/2-2=2;*/
class Solution3 {
public:
vector<int> v;
vector<bool> t;
int len;
int minSwapsCouples(vector<int>& row) {
v.resize(row.size());
t.resize(row.size());
len = row.size() / 2;
for (int i = 0; i<row.size(); i++)
v[row[i]] = i;
for(int i = 0; i<row.size(); i=i+2)
if (!t[row[i]]) {
help(row, row[i]);
len--;
}
return len;
}
private:
void help(vector<int>& row, int num) {
t[num] = true;
int temp = row[fun(v[num])];
t[temp] = true;
if (t[fun(temp)]) return;
help(row, fun(temp));
}
inline int fun(int& a) {
return a % 2 ? a - 1 : a + 1;
}
};