题解
用三个栈模拟。
#include <iostream>
#include <cstdio>
#include <stack>
#include <vector>
using namespace std;
int t, p, q;
bool solve()
{
vector< stack<int> > h(4);
int from, to;
for(int i = p; i >= 1; --i) h[1].push(i);
while(q--)
{
cin >> from >> to;
if(h[from].empty()) return false;
if(!h[to].empty() && h[from].top() > h[to].top()) return false;
h[to].push(h[from].top());
h[from].pop();
}
return true;
}
int main()
{
for(cin >> t; t--; )
{
cin >> p >> q;
cout << (solve() ? "legal" : "illegal") << endl;
}
return 0;
}