CCF 201509-4 高速公路 80分

#include
using namespace std;
const int maxn = 10010;

struct Edge{
    int v1, v2;
    bool operator < (const Edge & e) const{
        if(v1 == e.v1)
            return v2 < e.v2;
        else
            return v1 < e.v1;
    }
};

vector  >Map;
map J;
int degree[maxn];
int f[maxn];
stack q;
int n;

void Init()
{
    for(int i = 1; i <= n; i++)
        f[i] = -1;
}
int Find(int x)
{
    if(f[x] == -1)
        return x;
    else
        return f[x] = Find(f[x]);
}
void Merge(int x1, int x2)
{
    x1 = Find(x1);
    x2 = Find(x2);
    if(x1 != x2)
        f[max(x1,x2)] = min(x1, x2);
}

void dfs(int v)
{
    set :: iterator iter;
    for(iter = Map[v].begin(); iter != Map[v].end(); iter++)
    {
            int v1 = min(v, (*iter));
            int v2 = max(v, (*iter));
            Edge e;
            e.v1 = v1, e.v2 = v2;
            if(J[e]){
                J[e] = false;
                dfs((*iter));
            }
    }
    q.push(v);
}

int main()
{
    int m;
    cin  >> n >> m;
    for(int i = 0; i <= n; i++){
        set Set;
        Map.push_back(Set);
    }
    Init();
    //memset(Map, 0, sizeof(Map));
    for(int i = 0; i < m; i++){
        int v1, v2;
        cin >> v1 >> v2;
        Merge(v1, v2);
      //  cout << f[v1] << " " << f[v2] << endl;
        //Map[v1][v2] = Map[v2][v1] = 1;
        Map[v1].insert(v2);
        Map[v2].insert(v1);
        degree[v1]++, degree[v2]++;
        Edge e;
        e.v1 = min(v1,v2), e.v2 = max(v1, v2);
        J.insert(make_pair(e, true));
    }
    int tot1 = 0, tot2 = 0;
    for(int i = 1; i <= n; i++)
    {
        if(Find(i) == i){
            //cout << f[i] << " " << i << endl;
            tot2++;
        }
    }
    for(int i = 1; i <= n; i++)  //统计度为奇数的点的个数
        if(degree[i] % 2)
            tot1++;
    if(tot2 > 1|| (tot1 != 0 && tot1 != 2))
        cout << "-1" << endl;
    else {
        dfs(1);   //起点的确定要根据题意来定
        while(!q.empty()){
            cout << q.top() << " ";
            q.pop();
        }
    }
    return 0;
}

 

你可能感兴趣的:(CCF)