zoukankan      html  css  js  c++  java
  • hihocoder 第170周 Word Construction (dfs+剪枝)

    #1334 : Word Construction

    时间限制:10000ms
    单点时限:1000ms
    内存限制:256MB

    描述

    Given N words from the top 100 common words in English (see below for reference), select as many words as possible as long as no two words share common letters.

    Assume that the top 100 common words in English are:

    the be to of and a in that have i it for not on with he as you do at this but his by from they we say her she or an will my one all would there their what so up out if about who get which go me when make can like time no just him know take people into year your good some could them see other than then now look only come its over think also back after use two how our work first well even new want because any these give day most us

    输入

    The first line contains an integer N, denoting the number of words. (1 ≤ N ≤ 40)  

    The second line contains N words from the top 100 common words.

    输出

    Output the most number of words can be selected.

    样例输入
    8
    the be to of and a in that 
    样例输出
    4

    题意:

    给出N个单词(1 ≤ N ≤ 40),在满足各个单词之间没有重复字母的情况下,求能选取最多多少个单词。

    题解:

    dfs+剪枝,因为要求字母不重复

    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <cstdio>
    using namespace std;
    const int N = 40 + 10;
    int a[200] = {0}, vis[N] = {0};
    string s[N];
    int ans = 0, n;
    int dfs(int num)
    {
        int tmp = 0;
        vis[num] = 1;
        for(int i = 0; i < n; i++) {
            if(vis[i])
                continue;
            int len = s[i].length();
            //出现重复字母
            for(int j = 0; j < len; j++) {
                if(a[s[i][j]])
                    len = -1;
            }
            if(len == -1)
                continue;
            for(int j = 0; j < len; j++) {
                a[s[i][j]]++;
            }
            tmp = max(tmp, dfs(i));
            for(int j = 0; j < len; j++) {
                a[s[i][j]]--;
            }
        }
        vis[num] = 0;
        return tmp + 1;
    }
    int  main()
    {
        cin >> n;
        for(int i = 0; i < n; i++) {
            cin >> s[i];
        }
        int ans = 0;
        for(int i = 0; i < n; i++) {
            memset(vis, 0, sizeof(vis));
            memset(a, 0, sizeof(a));
            for(int j = 0; j < s[i].length(); j++)
                a[s[i][j]]++;
            ans = max(ans, dfs(i));
        }
        printf("%d
    ", ans);
        return 0;
    }
  • 相关阅读:
    JUC学习笔记--从阿里Java开发手册学习线程池的正确创建方法
    1.初识Python
    学会 Debug
    如何找出nginx配置文件的所在位置?
    一个技术人,如何做到比别人更突出
    生产环境如何快速跟踪、分析、定位问题-Java
    如何优化代码中大量的if/else,switch/case?
    UML类图几种关系的总结
    DateUtils常用方法
    如何存储和表示数字—二进制(一)
  • 原文地址:https://www.cnblogs.com/yu0111/p/7635747.html
Copyright © 2011-2022 走看看