Source Code
#include "bits/stdc++.h"

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double dd;
#define all(v) v.begin(),v.end()
#define endl "\n"
#define clr(n, r) memset(n,r,sizeof(n))
typedef bitset<10> MASK;

void fast() {
    cin.tie(0);
    cin.sync_with_stdio(0);
}

struct node {
    int v, idx;

    bool operator < (node &x) const {
        return v < x.v;
    }
};

vector<int> ans;

const int MAX = 5e5  + 10;
int selfloop[MAX];
int n, m, vis[MAX];
vector<vector<node>> adj(MAX);
vector<set<int>> distinct(MAX);
bool ok = 1;

void dfs(int u) {
    sort(all(adj[u]));
    vis[u] = 1;
    int cnt = selfloop[u];
    int to = -1;
    for (int i = 1; i <adj[u].size() ; ++i) {
        if(adj[u][i].v!=adj[u][i-1].v){
            cnt += selfloop[adj[u][i].v];
        }
    }
    for (auto i : adj[u]) {
        if (i.v == u)ans.push_back(i.idx);
        else {
          if (!vis[i.v]) {
              if (selfloop[i.v]) {
                  continue;
              }
              to = i.v;
                ans.push_back(i.idx);
            }
        }
    }
    for (auto i : adj[u]) {
        if (i.v != u)
             if (!vis[i.v])
                if (selfloop[i.v]) {
                    to = i.v;
                    break;
                }
    }
    if(~to ){
        for (auto i : adj[u]) {
            if (i.v != u)
                if (!vis[i.v])
                    if (selfloop[i.v]) {
                        ans.push_back(i.idx);
                    }
        }
    }

    for (auto i : adj[u]) {
        if (i.v != u) {
            if (to == i.v)continue;
            vis[i.v] = 1;
        }
    }

    if (cnt > 2)ok = 0;
    else if (~to){
        dfs(to);
    }

}

int main() {
    fast();
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        int k;
        cin >> k;
        int u, v;
        cin >> u;
        v = u;
        if (k == 2)cin >> v;
        adj[u].push_back({v, i});
        if(k>1)adj[v].push_back({u, i});
        if (u == v)selfloop[u] = 1;
    }
    for (int i = 1; i <= m; ++i) {
        if (selfloop[i] && !vis[i])dfs(i);
    }
    for (int i = 1; i <= m; ++i) {
        if (!vis[i])dfs(i);
    }
    int cur = 1;
    if(!ok||ans.size()!=n)return cout<<-1,0;
    for(auto i : ans)cout<<i<<" ";
}
Copy
Gym 7eem
GNU G++17
21 ms
35.7 MB
Wrong Answer