PTA珍珠项链
一、题目描述

二、解题思路
并查集模板题,只不过输出的时候不是输出a[i]而是要再查一次,输出find(a[i])
三、代码实现
1 #include "bits/stdc++.h" 2 #define PII pair<int,int> 3 #define rep(i,z,n) for(int i = z;i <= n; i++) 4 #define per(i,n,z) for(int i = n;i >= z; i--) 5 #define ll long long 6 #define db double 7 #define vi vector<int> 8 #define debug(x) cerr << "!!!" << x << endl; 9 using namespace std; 10 //从某个串中把某个子串替换成另一个子串 11 string& replace_all(string& src, const string& old_value, const string& new_value) { 12 // 每次重新定位起始位置,防止上轮替换后的字符串形成新的old_value 13 for (string::size_type pos(0); pos != string::npos; pos += new_value.length()) { 14 if ((pos = src.find(old_value, pos)) != string::npos) { 15 src.replace(pos, old_value.length(), new_value); 16 } 17 else break; 18 } 19 return src; 20 } 21 inline ll read() 22 { 23 ll s,r; 24 r = 1; 25 s = 0; 26 char ch = getchar(); 27 while(ch < '0' || ch > '9'){ 28 if(ch == '-') 29 r = -1; 30 ch = getchar(); 31 } 32 while(ch >= '0' && ch <= '9'){ 33 s = (s << 1) + (s << 3) + (ch ^ 48); 34 ch = getchar(); 35 } 36 return s * r; 37 } 38 inline void write(ll x) 39 { 40 if(x < 0) putchar('-'),x = -x; 41 if(x > 9) write(x / 10); 42 putchar(x % 10 + '0'); 43 } 44 int a[300010]; 45 int n,m; 46 void init() 47 { 48 rep(i,1,n + 1) 49 a[i] = i; 50 } 51 int find(int u) 52 { 53 return u == a[u] ? u :a[u] = find(a[u]); 54 } 55 int main() 56 { 57 int t; 58 t = read(); 59 while(t--){ 60 cin >> n >> m; 61 init(); 62 while(m--){ 63 int u,v; 64 cin >> u >> v; 65 u = find(u); 66 v = find(v); 67 if(u != v) 68 a[u] = v; 69 } 70 rep(i,1,n) 71 cout << find(a[i]) << ' '; 72 cout << endl; 73 } 74 return 0; 75 }
本文来自博客园,作者:{scanner},转载请注明原文链接:{https://home.cnblogs.com/u/scannerkk/}

浙公网安备 33010602011771号