75分求猪?
查看原帖
75分求猪?
1245275
hundunlilun1楼主2024/10/19 21:41

思路是从图上只有一条路通往那个节点的节点开始逐步扩散的进行BFS。c存结果,b用来存某个点周围编号最大的点。点取值用l和r贪。

#include<bits/stdc++.h>
using namespace std;
int n,l,r;
struct Node{
    int fa,x;
};

vector<int> a[100010];
int b[100010];
int c[100010];
queue<Node> q;

int main(){
    int _;
    cin>>_;
    while(_--){
        cin>>n;
        for(int i=0; i<=n; i++) c[i]=b[i]=0;
        for(int i=1; i<n; i++){
            int u,v;
            cin>>u>>v;
            u--, v--;
            a[u].push_back(v);
            a[v].push_back(u);
        }
        for(int i=0; i<n; i++){
            if(a[i].size()==1) q.push((Node){-1, i});
        }
        l=1,r=n;
        while(!q.empty()){
            Node pos = q.front();
            q.pop();
            if(pos.fa==-1){
                c[pos.x]=r;
                for(auto x : a[pos.x]){
                    if(x==pos.fa||c[x]!=0) continue;
                    q.push((Node){pos.x, x});
                    b[x]=max(b[x], r);
                }
                r--;
                continue;
            }
            if(c[pos.x]!=0) continue;
            if(b[pos.x]+r<=n+1){
                c[pos.x]=r;
                for(auto x : a[pos.x]){
                    if(x==pos.fa||c[x]!=0) continue;
                    q.push((Node){pos.x, x});
                    b[x]=max(b[x], r);
                }
                r--;
            }else{
                c[pos.x]=l;
                for(auto x : a[pos.x]){
                    if(x==pos.fa||c[x]!=0) continue;
                    q.push((Node){pos.x, x});
                    b[x]=max(b[x], l);
                }
                l++;
            }
        }
        for(int i=0; i<n; i++){
            cout<<c[i]<<" ";
        }cout<<'\n';

        
        for(int i=0; i<=n; i++){
            a[i].clear();
        }
    }

    return 0;
}
2024/10/19 21:41
加载中...