跳到正文

个人记录

111

1232RvE约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll T,n;
ll  b[505][505];
ll a[505],p[505];
vector<int> r(505,0);
        ll find(ll x){
            if (p[x]!=x){
                p[x]=find(p[x]);
            }
            return p[x];
        }
        bool ust(ll x,ll y){
            x = find(x);
            y = find(y);
            if (x==y)return 0;
            if(r[x]<r[y])p[x]=y;
            else if (r[x]>r[y]) p[y] = x;
            else{
                p[y] = x,r[x]++;
            }
            return 1;
        }
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin>>T;
    while(T--){
        cin>>n;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                cin>>b[i][j];
            }
        }
        for(int i=0;i<n;i++){
            a[i]=b[i][i];
        }
        vector<pair<int, int>> edges;
        for(int i=0;i<n;i++){
            for (int j=i+1;j<n;j++){
                if ((a[i]^a[j])==b[i][j]){
                    edges.push_back({i,j});
                }
            }
        }


        for (int i=0;i<n;i++) {
            p[i]=i;
        }


        vector<pair<int,int> > tre;
        for (auto &e:edges){
            if (tre.size()==n-1) break;
            int u=e.first,v=e.second;
            if (ust(u,v)){
                tre.push_back(e);
            }
        }

        if(tre.size()<n-1&&n==2){
            tre.push_back({0,1});
        }

        for(int i=0;i<n;i++){
            if(i>0) cout <<" ";
            cout<<a[i];
        }
        cout<<'\n';

        for(auto &e:tre){
            cout<<e.first+1<<" "<<e.second+1<<'\n';
        }
    }

    return 0;
}
原文