60pts求助,tle了
查看原帖
60pts求助,tle了
535407
Retr0_Gu楼主2023/7/25 19:34
#include <bits/stdc++.h>
#define to(i) edge[i].to
#define next(i) edge[i].next
using namespace std;

const int N = 2e3 + 1, M = 1e4 + 1;

struct Edge{
    int to;
    int next;
}edge[M];

struct Flight{
    int id;
    int k;
    Flight(int id, int k) : id(id), k(k){};
};

int cnt, k[N], head[N], in[N], tmp[N], ans[N];

void add_edge(int u, int v){
    to(++cnt) = v;
    next(cnt) = head[u];
    head[u] = cnt;
    in[v]++;
}

bool operator<(Flight l, Flight r){
    return l.k < r.k;
}

int topo_sort(int n, int x){
    priority_queue <Flight> pq;
    for (int i = 1; i <= n; i++){
        if (!in[i]) pq.push(Flight(i, k[i]));
        tmp[i] = in[i];
    }
    while (!pq.empty()){
        int u = pq.top().id, uk = pq.top().k;
        pq.pop();
        if (u == x || uk < n) continue;
        ans[n--] = u;
        for (int i = head[u]; i; i = next(i))
            if (!--tmp[to(i)]) pq.push(Flight(to(i), k[to(i)]));
    }
    return n;
}

int main(){
    int n, m;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
        scanf("%d", &k[i]);
    while (m--){
        int a, b;
        scanf("%d%d", &a, &b);
        add_edge(b, a);
    }
    topo_sort(n, 0);
    for (int i = 1; i <= n; i++)
        printf("%d ", ans[i]);
    printf("\n");
    for (int i = 1; i <= n; i++)
        printf("%d ", topo_sort(n, i));
    return 0;
}
2023/7/25 19:34
加载中...