Codeforces Round #628 (Div. 2)------Ehab and Path-etic MEXs

题目:
You are given a tree consisting of n nodes. You want to write some labels on the tree’s edges such that the following conditions hold:
Every label is an integer between 0 and n−2 inclusive.
All the written labels are distinct.
The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn’t written on any edge on the unique simple path from node u to node v.

Input
The first line contains the integer n (2≤n≤105) — the number of nodes in the tree.
Each of the next n−1 lines contains two space-separated integers u and v (1≤u,v≤n) that mean there’s an edge between nodes u and v. It’s guaranteed that the given graph is a tree.

Output
Output n−1 integers. The ith of them will be the number written on the ith edge (in the input order).

样例:

输入1:
3
1 2
1 3
输出1:
0
1

输入2:
6
1 2
1 3
2 4
2 5
5 6
输出2:
0
3
2
4
1

题意:
给定一棵具有 n 个点的树,对树边标号为 0,1,2,…,n−2 。定义 MEX(u,v) :点 u 到 v 的路径上最小的未出现的标号;现请你给出一种构造方案使得对于所有 MEX(u,v) 的最大值最小

思路:
如果存在某一个节点度数大于等于3,将其相邻的三条边编号0,1,2…。
这样就保证了任选一条路径不会同时存在着3个数

愉快AC:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
struct node{
    int x, y;
    int p;
    node(){};
    node(int x_, int y_){x = x_, y = y_;}
    bool operator < (const node &a) const{
        return x == a.x ? y < a.y : x < a.x;
    }
}st[maxn];
vector<int>v[maxn];
map<node, int>mp;
int vis[maxn];//存储边的度数
int main()
{
    int n; cin >> n;
    for(int i = 2; i <= n; i++){
        int a, b; cin >> a >> b;
        if(a > b)
            swap(a, b);
        vis[a]++; vis[b]++;
        st[i - 1] = node(a, b);
        st[i - 1].p = i;
        v[a].push_back(b);
        v[b].push_back(a);
        mp[node(a, b)] = -1;
    }
    int cnt = 0;
    for(int i = 1; i <= n; i++){
        if(vis[i] > 2){
            for(int j = 0; j < v[i].size(); j++){
                int x = i, y = v[i][j];
                if(x > y)
                    swap(x, y);
                mp[node(x, y)] = cnt;
                cnt++;
            }
            break;
        }
    }
    for(int i = 1; i < n; i++){
        if(mp[node(st[i].x, st[i].y)] != -1)
            cout << mp[node(st[i].x, st[i].y)] << endl;
        else{
            cout << cnt << endl;
            cnt++;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值