【題解】Codeforces 1361A. Johnny and Contribution

【題目敘述】http://codeforces.com/contest/1361/problem/A

#include <iostream>
#include <set>
#include <vector>
#include <queue>
using namespace std;
 
int n, m, a, b, t[500005], used[500005];
vector <int> v[500005], ans;
set <int> st[500005];
 
int main() {
    cin >> n >> m;
    for (int i = 0; i < m; i++){
        cin >> a >> b;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    queue <int> q;
    for (int i = 1; i <= n; i++){
        cin >> t[i];
        if (t[i] == 1){
            q.push(i);
            ans.push_back(i);
            used[i] = 1;
        }
    }
    for (int i = 1; i <= n; i++){
        for (int j:v[i]){
            if (t[i] == t[j]){
                cout << -1 << "\n";
                return 0;
            }
        }
    }
    while (!q.empty()){
        int now = q.front();
        q.pop();
        for (int i:v[now]){
            if (used[i]) continue;
            st[i].insert(t[now]);
            if (t[i] == t[now]+1){
                for (int j = 1; j <= t[now]; j++){
                    if (!st[i].count(j)){
                        cout << -1 << "\n";
                        return 0;
                    }
                }
                ans.push_back(i);
                q.push(i);
                used[i] = 1;
            }
        }
    }
    if (ans.size() != n){
        cout << -1 << "\n";
        return 0;
    }
    for (int i:ans){
        cout << i << " ";
    }
    cout << "\n";
}
分享本文 Share with friends