RC-u4 拆积木

#include <bits/stdc++.h>
using namespace std;

const int N = 1e3 + 10, M = 1e6 + 10;

int a[2][N];
vector<int> v;

vector<int> tp;
short int din[M];

int h[M], e[M], ne[M], idx;

void add(int a, int b)
{
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx ++;
}

bool toposort()
{
    priority_queue<int, vector<int>, greater<int>> q;
    for(auto i : v) if(din[i] == 0) q.push(i);

    while(!q.empty())
    {
        int t = q.top();
        q.pop();
        tp.push_back(t);
        for(int i = h[t]; ~i; i = ne[i])
        {
            int k = e[i];
            if(-- din[k] == 0) q.push(k);
        }
    }
    if(tp.size() == v.size()) return true;
    else return false;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    memset(h, -1, sizeof h);
    
    int n, m;
    cin >> n >> m;
    // if(n == 1000 && m == 1000) return -1;
    for(int i = 0; i < n; i ++ )
    {
        for(int j = 0; j < m; j ++ )
        {
            int u = i & 1;
            cin >> a[u][j];
            v.emplace_back(a[u][j]);
            if(i == 0) continue;
            if(a[1 - u][j] != a[u][j])
            add(a[1 - u][j], a[u][j]), din[a[u][j]] ++;
        }
    }
    
    //用set或者unordered_set进行去重会有内存超限的问题
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());
    
    if(toposort())
    {
        for(auto i = 0; i < tp.size(); i ++ )
        {
            cout << tp[i];
            if(i != tp.size() - 1) cout << " ";
        }
    }
    else
    {
        for(auto i = 0; i < tp.size(); i ++ )
        {
            cout << tp[i] << ' ';
        }
        cout << "Impossible";
     }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值