zoukankan      html  css  js  c++  java
  • SPOJ:Lexicographically Smallest(并查集&排序)

    Taplu and Abhishar loved playing scrabble. One day they thought of inventing a new game using alphabet tiles. Abhishar wrote a string using tiles and gave a set of pairs (i,j) to Taplu. Pair “i, j” (0 based indexing) means that Taplu can swap the i’th and j’th tile in the string any number of times.  He then asks Taplu to give the lexicographically smallest string that can be produced by doing any number of swaps on the original string.

    Input

    First line contains T(1<=T<=10), the number of testcases.

    First line of each test case contains the initial string S. Length of Sttring is len(1<=len<=100000).

    Next line contains the number of pairs M (1<=M<=100000).

    Next M lines contains pairs i j that means ith character can be swapped with jth character.

    Note - i and j can be same and same i,j pair can occur twice.

    Output

    For each testcase output the lexicographically smallest string that can be made from the initial string.

    Example

    Input:

    1
    lmaf
    3
    0 1
    1 2
    2 3 Output: aflm

    题意:给定字符串S,以及M对关系(i,j),表示i位置和j位置上的字符可以交换任意次。现在让你交换,得到最小字典序的S。

    思路:我们把有()关系的i,j对放到一个并查集里,不难证明,一个并查集内的任意两个位置是可以互换的,所以我们把分别把所有并查集排序即可。

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn=200010;
    char c[maxn],ans[maxn];
    int fa[maxn],group[maxn],tot;
    vector<int>G[maxn];
    struct in { int id; }s[maxn]; int num;
    bool cmp(in w,in v){ return c[w.id]<c[v.id]; }
    int find(int x){
        if(x==fa[x]) return x;
        fa[x]=find(fa[x]);
        return fa[x];
    }
    int main()
    {
        int T,N,M,a,b,faa,fab,i,j;
        scanf("%d",&T);
        while(T--){
            scanf("%s%d",c+1,&M);
            tot=0; N=strlen(c+1);
            memset(group,0,sizeof(group));
            for(i=1;i<=N;i++) fa[i]=i;
            for(i=1;i<=M;i++){
                scanf("%d%d",&a,&b);
                faa=find(a+1); fab=find(b+1);
                if(faa!=fab) fa[faa]=fab;
            }
            for(i=1;i<=N;i++){
                faa=find(i);
                if(!group[faa]){
                   group[faa]=++tot;
                   G[tot].clear();
                }
                G[group[faa]].push_back(i);
            }
            for(i=1;i<=tot;i++){
                num=0;
                for(j=0;j<G[i].size();j++) s[++num].id=G[i][j];
                sort(s+1,s+num+1,cmp);
                for(j=0;j<G[i].size();j++) ans[G[i][j]]=c[s[j+1].id];
            }
            for(i=1;i<=N;i++) printf("%c",ans[i]);  printf("
    ");
        }
        return 0;
    }
  • 相关阅读:
    JavaScript 中继承的一些示例
    测试ASP_NET 生命周期
    Web 设计师的 50 个超便利工具[下]
    关于ASP.NET 中站点地图sitemap 的使用
    早该知道的 7 个JavaScript 技巧[转]
    C# 浅拷贝与深拷贝区别
    HTML 中表格table 的相关知识
    理解值与引用[学习]
    关于CSS 3 及浏览器兼容性问题
    SQL Server 的存储过程[转]
  • 原文地址:https://www.cnblogs.com/hua-dong/p/9089684.html
Copyright © 2011-2022 走看看