D. Secret Passwords

本文探讨了如何使用并查集数据结构处理字符串中重复字符的问题,特别关注于将输入转换为最多包含26个小写字母的独特字符串集合。通过并查集优化字符串比较过程,确保每个点只有一个父节点和子节点,从而简化了处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:D. Secret Passwords

总结:题目要求输入必须小写的英文单词。所以对于一串字符串去掉重复的最多剩下26个字母。
对于一串字符串,每两个不同的,一定是表示同一个。所以这时候就可以用并查集。但这里用并查集需要注意一点就是并查集中每个点的父亲节点只有一个,每个节点的儿子节点也只有一个。所以我加了一个这个if(fx > fy) swap(fx,fy);

#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int>P;
const int N = 2e5+10;

map<P,int>v;
map<int,int>vis;
string s;
int n;
int fa[50];
set<int>st;
map<P,int>::iterator it;

int Find(int x){
    if(fa[x] == -1) return x;
    else return fa[x] = Find(fa[x]);
}

void traver(){
    for(int i = 1;i <= 26;i++){
        printf("%3d",i);
    }
    cout<<endl;
    for(int i = 1;i <= 26;i++){
        printf("%3d",fa[i]);
    }
    cout<<endl<<endl;
}

int main(){
  //  freopen("in.txt","r",stdin);
    memset(fa,-1,sizeof fa);
    cin >> n;
    for(int i = 0;i < n;i++){
        cin >> s;
        sort(s.begin(),s.end());
        int len = unique(s.begin(),s.end())-s.begin();
        if(len == 1){
            int x = s[0]-96;
            st.insert(x);
            continue;
        }
        for(int i = 0;i < len;i++){
            for(int j = i+1;j < len;j++){
                int x = s[i]-96;
                int y = s[j]-96;
                if(v[P(x,y)]) continue;
                v[P(x,y)] = 1;
            }
        }
    }
    for(it = v.begin();it != v.end();it++){
        P t = it->first;
        int x = t.first;
        int y = t.second;
        st.erase(x);
        st.erase(y);
        int fx = Find(x);
        int fy = Find(y);
        if(fx > fy) swap(fx,fy);
        if(fx != fy){
            fa[fy] = fx;
        }
       // cout<<x<<" "<<y<<endl;
       // traver();
    }

    int ans = 0;
    for(int i = 1;i <= 26;i++){
        if(fa[i] != -1){
            if(!vis[fa[i]]) ans++;
            vis[fa[i]] = 1;
        }
    }

    cout<<(ans+st.size())<<endl;

    return 0;
}
//2545124

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值