extern "C" int *find_pairs(int n, int m, int u[], int v[])
{
using namespace std;
auto check = [](int x1, int y1, int x2, int y2) -> bool
{ return x1 != x2 && x1 != y2 && y1 != x2 && y1 != y2; };
int *ret = (int *)malloc(m * sizeof(int));
vector<int> ans(m + 1);
vector<pair<int, int>> points(m + 1);
for (int i = 1; i <= m; i++)
points[i].first = u[i - 1], points[i].second = v[i - 1];
auto solve = [&ans, m, &points, &check](int id1, int id2) -> void
{
for (int i = 1; i <= m; i++)
if (check(points[i].first, points[i].second, points[id1].first, points[id1].second))
ans[i] = id1;
for (int i = 1; i <= m; i++)
if (check(points[i].first, points[i].second, points[id2].first, points[id2].second))
ans[i] = id2;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= m && ans[i] == 0; j++)
if (check(points[i].first, points[i].second, points[j].first, points[j].second))
ans[i] = j;
};
bool flag = false;
for (int i = 2; i <= m && !flag; i++)
if (check(points[i].first, points[i].second, points[1].first, points[1].second))
solve(1, i), flag = true;
if (!flag)
{
int id;
for (id = 1; id <= m; id++)
if (points[id].first != points[1].first && points[id].second != points[1].first)
break;
if (id <= m)
{
auto fd = [&points, m](int x, int y) -> int
{
for (int i = 1; i <= m; i++)
if (x == points[i].first && y == points[i].second)
return i;
return 0;
};
int res1 = fd(points[1].first, points[id].second);
int res2 = fd(points[id].second, points[1].first);
if (res1)
{
for (int i = 1; i <= m && !flag; i++)
if (check(points[res1].first, points[res1].second, points[i].first, points[i].second))
solve(i, res1), flag = true;
}
else if (res2)
{
for (int i = 1; i <= m && !flag; i++)
if (check(points[res2].first, points[res2].second, points[i].first, points[i].second))
solve(i, res2), flag = true;
}
}
}
for (int i = 1; i <= m; i++)
ret[i - 1] = ans[i] - 1;
return ret;
}