[bzoj3012][Usaco2015 Dec][字典树][Top序]First!

本文介绍了一种算法,用于确定在重新排列字母顺序的情况下,哪些字符串能够成为字典序最小的串。通过构建 Tire 树和使用拓扑排序来解决这一问题。

Description

Bessie has been playing with strings again. She found that by changing
the order of the alphabet she could make some strings come before all
the others lexicographically (dictionary ordering). For instance
Bessie found that for the strings “omm”, “moo”, “mom”, and “ommnom”
she could make “mom” appear first using the standard alphabet and that
she could make “omm” appear first using the alphabet
“abcdefghijklonmpqrstuvwxyz”. However, Bessie couldn’t figure out any
way to make “moo” or “ommnom” appear first. Help Bessie by computing
which strings in the input could be lexicographically first by
rearranging the order of the alphabet. To compute if string X is
lexicographically before string Y find the index of the first
character in which they differ, j. If no such index exists then X is
lexicographically before Y if X is shorter than Y. Otherwise X is
lexicographically before Y if X[j] occurs earlier in the alphabet than
Y[j].

给定n个总长不超过m的互不相同的字符串,现在你可以任意指定字符之间的大小关系。问有多少个串可能成为字典 序最小的串,并输出这些串。n <=
30,000 , m <= 300,000

Input

  • Line 1: A single line containing N (1 <= N <= 30,000), the number of strings Bessie is playing with.

  • Lines 2..1+N: Each line contains a non-empty string. The total number of characters in all strings will be no more than 300,000. All
    characters in input will be lowercase characters ‘a’ through ‘z’.
    Input will contain no duplicate strings.

Output

  • Line 1: A single line containing K, the number of strings that
    could be lexicographically first.

  • Lines 2..1+K: The (1+i)th line should contain the ith string that
    could be lexicographically first. Strings should be output in the same
    order they were given in the input.

Sample Input

4

omm

moo

mom

ommnom

Sample Output

2

omm

mom

题解

Tire+top序
考虑单词可以成为第一的情况

1、没有任何单词是他的前缀。因为如果他的某一前缀是一个单词的话,那么他一定不是第一个
2、他的所有字母一定比和他在Tire树中拥有同一个父亲的兄弟高级

首先对单词建Tire树,记录单词在Tire树中出现的位置
枚举每个单词,先在Tire树中找到这个单词的位置。如果在找到这个单词的位置之前,发现了另一个单词。那么排除这一个单词。因为有单词成为他的前缀了
倘若找到了这个单词的位置,那么在寻找的过程中我们建top序
对于x,假设x>y这个字母,我们就x -> y连一条边。之后跑top序判环就好

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
struct node
{
    int x,y,next;
}a[1111000];int len,last[27];
void ins(int x,int y)
{
    len++;a[len].x=x;a[len].y=y;
    a[len].next=last[x];last[x]=len;
}
struct Tire
{
    int c[27],s;
    Tire(){memset(c,-1,sizeof(c));}
}tr[311000];int tot,root;
void add(char *st,int op)
{
    int len=strlen(st+1),x=root;
    for(int i=1;i<=len;i++)
    {
        int y=st[i]-'a'+1;
        if(tr[x].c[y]==-1)tr[x].c[y]=++tot;
        x=tr[x].c[y];
    }
    tr[x].s=op;
}
int ru[27];
bool v[27];
bool top()
{
    memset(v,true,sizeof(v));
    for(int i=1;i<=26;i++)
    {
        int x=0;
        for(int j=1;j<=26;j++)if(ru[j]==0 && v[j]==true){x=j;break;}
        if(x==0)return false;
        v[x]=false;
        for(int k=last[x];k;k=a[k].next)ru[a[k].y]--;
    }
    return true;
}
int ans[31000],cnt,n;
int tmp[31000],now;//记录每个串开头
char ss[310000],s[310000];//串接起来的结果 
int main()
{
    scanf("%d",&n);                                                                                                                                                                                            
    now=root=0;
    for(int i=1;i<=n;i++)
    {
        scanf("%s",ss+1);
        add(ss,i);tmp[i]=now+1;
        int len=strlen(ss+1);
        for(int j=1;j<=len;j++)s[++now]=ss[j];
    }
    cnt=0;tmp[n+1]=now+1;
    for(int i=1;i<=n;i++)//枚举每个单词 
    {
        len=0;memset(last,0,sizeof(last));memset(ru,0,sizeof(ru));
        int x=root;bool bk=false;
        for(int j=tmp[i];j<tmp[i+1];j++)
        {
            int y=s[j]-'a'+1;
            if(tr[x].s>0){bk=true;break;}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
            //x=tr[x].c[y];
            for(int k=1;k<=26;k++)if(tr[x].c[k]!=-1 && k!=y){ins(y,k);ru[k]++;}
            x=tr[x].c[y];   
        }
        if(bk==true)continue;//前面有比我更短的 
        if(top())ans[++cnt]=tr[x].s;
    }
    printf("%d\n",cnt);
    for(int i=1;i<=cnt;i++)
    {
        for(int j=tmp[ans[i]];j<tmp[ans[i]+1];j++)printf("%c",s[j]);
        printf("\n");
    }
    return 0;
}
### BZOJ1728 Two-Headed Cows (双头牛) 的解题思路 #### 题目概述 BZOJ1728 是一道经典的图论问题,题目描述了一群双头牛之间的关系网络。每只双头牛可以看作是一个节点,而它们的关系则构成了边。目标是从这些关系中找出满足特定条件的最大子集。 此问题的核心在于利用 **二分查找** 和 **染色法** 来验证是否存在符合条件的子图结构[^1]。 --- #### 解题核心概念 ##### 1. 图模型构建 该问题可以通过无向图建模,其中每个顶点代表一只双头牛,边表示两只双头牛之间存在某种关联。最终的目标是在这个图中找到最大的独立集合(Independent Set),即任意两个顶点都不相连的一组顶点[^2]。 ##### 2. 二分查找的应用 为了高效求解最大独立集大小 \( k \),采用二分策略来逐步逼近最优解。具体来说,在区间 [0, n] 中通过不断调整上下界寻找可能的最大值 \( k \)[^3]。 ##### 3. 染色法验证可行性 对于当前假设的最大独立集大小 \( mid \),尝试从原图中选取恰好 \( mid \) 个顶点构成候选集合,并检查其是否形成合法的独立集。这一过程通常借助 BFS 或 DFS 实现,同时配合颜色标记技术区分已访问状态以及检测冲突情况[^4]。 以下是基于 Python 的伪代码实现: ```python from collections import deque def bfs_coloring(graph, start_node): queue = deque() color_map = {} # 初始化起点的颜色为 0 color_map[start_node] = 0 queue.append(start_node) while queue: current = queue.popleft() for neighbor in graph[current]: if neighbor not in color_map: # 给邻居分配相反的颜色 color_map[neighbor] = 1 - color_map[current] queue.append(neighbor) elif color_map[neighbor] == color_map[current]: return False # 如果发现相邻节点有相同颜色,则无法完成有效染色 return True def is_possible_to_select_k(graph, nodes_count, target_size): from itertools import combinations all_nodes = list(range(nodes_count)) possible_combinations = combinations(all_nodes, target_size) for subset in possible_combinations: subgraph = {node: [] for node in subset} valid_subset = True for u in subset: for v in graph[u]: if v in subset and v != u: subgraph[u].append(v) # 对子图进行染色测试 colors_used = set() coloring_success = True for node in subset: if node not in colors_used: success = bfs_coloring(subgraph, node) if not success: coloring_success = False break if coloring_success: return True # 找到一个有效的组合即可返回成功标志 return False def binary_search_max_independent_set(graph, total_nodes): low, high = 0, total_nodes best_result = 0 while low <= high: mid = (low + high) // 2 if is_possible_to_select_k(graph, total_nodes, mid): best_result = mid low = mid + 1 else: high = mid - 1 return best_result ``` --- #### 复杂度分析 上述算法的时间复杂度主要取决于以下几个方面: - 枚举所有可能的子集规模:\( O(\binom{n}{k}) \), 其中 \( k \) 表示当前试探的独立集大小。 - 子图构造与染色检验操作:每次调用 `bfs_coloring` 函数需遍历整个子图,最坏情况下时间开销接近线性级别 \( O(k^2) \). 综合来看整体效率较高但仍有优化空间[^5]. --- #### 总结 通过对 BZOJ1728 进行深入剖析可知,合理运用二分加染色的方法能够显著提升解决问题的能力。这种方法不仅适用于本题场景下寻找最大独立集的任务需求,同时也可推广至其他相似类型的 NP 完全难题处理之中[^6]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值