设备配置数据排序
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
unordered_map<int, vector<int>> graph;
unordered_map<int, int> indegree;
unordered_set<int> nodes;
unordered_map<int, int> lvl;
int head = -1, tail = -1;
for (int i = 0; i < n; ++i)
{
int a, b, c;
cin >> a >> b >> c;
if (lvl.find(a) == lvl.end())
{
lvl[a] = i;
}
if (a == b && c == -1)
{
head = a;
}
else if (a == c && b == -1)
{
tail = a;
}
else if (a == b && c != -1)
{
indegree[c]++;
graph[a].push_back(c);
}
else if (a == c && b != -1)
{
indegree[a]++;
graph[b].push_back(a);
}
if (a != -1) nodes.insert(a);
if (b != -1) nodes.insert(b);
if (c != -1) nodes.insert(c);
}
queue<int> q;
for (int k : nodes)
{
if (indegree[k] == 0)
{
q.push(k);
}
}
vector<int> res;
int cnt = 0;
while (!q.empty())
{
int size = q.size();
cnt += size;
vector<int> tmp;
for (int i = 0; i < size; ++i)
{
int u = q.front();
q.pop();
if (u != head && u != tail)
{
tmp.push_back(u);
}
for (int v : graph[u])
{
indegree[v]--;
if (indegree[v] == 0)
{
q.push(v);
}
}
}
sort(tmp.begin(), tmp.end(), [&](int x, int y)
{
return lvl[x] < lvl[y];
});
res.insert(res.end(), tmp.begin(), tmp.end());
}
if (cnt == nodes.size())
{
if (head != -1 && tail != -1)
{
cout << head << " ";
for (int val : res) cout << val << " ";
cout << tail << endl;
}
else if (head == -1 && tail != -1)
{
for (int val : res) cout << val << " ";
cout << tail << endl;
}
else if (head != -1 && tail == -1)
{
cout << head << " ";
for (int val : res) cout << val << " ";
cout << endl;
}
else
{
for (int val : res) cout << val << " ";
cout << endl;
}
}
else
{
cout << -1 << endl;
}
return 0;
}