别的方法过了,但是不明白为什么这个方法只有10分
查看原帖
别的方法过了,但是不明白为什么这个方法只有10分
833124
BIOS楼主2023/9/4 22:03
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 1e5 + 5;
int h[N], e[N], ne[N], idx, n, m, a, b, res[N], top;
void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
struct node
{
    int d, lim, id;
    bool operator>(const node &t) const
    {
        if (t.lim == lim && t.d == d)
            return id > t.id;
        else if (t.d == d)
            return lim > t.lim;
        return d > t.d;
    }
} t[N];
priority_queue<node, vector<node>, greater<node>> q;
bool topsort()
{
    node p;
    int id, j;
    while (q.size())
    {
        p = q.top(), q.pop();
        if (p.d)
            break;
        id = p.id, res[++top] = id;
        for (int i = h[id]; ~i; i = ne[i])
            j = e[i], t[j].d--, q.push(t[j]);
    }
    return top == n;
}
int main()
{
    ios::sync_with_stdio(false), cin.tie(0);
    int T;
    cin >> T;
    while (T--)
    {
        cin >> n >> m, memset(h, -1, sizeof(h)), top = idx = 0;
        for (int i = 1; i <= n; i++)
            t[i].d = 0, t[i].id = t[i].lim = i;
        while (m--)
        {
            cin >> a >> b, add(a, b);
            t[a].lim = min(t[a].lim, t[b].lim), t[b].d++;
        }
        for (int i = 1; i <= n; i++)
            q.push(t[i]);
        if (topsort())
            for (int i = 1; i <= n; i++)
                cout << res[i] << " ";
        else
            cout << "Impossible! ";
        cout << "\n";
    }
}

我寻思一直维护一个堆来做的,难道一些排序的性质推错了?

2023/9/4 22:03
加载中...