uva11732 "strcmp()" Anyone?

11732 “strcmp()” Anyone?


strcmp() is a library function in C/C++ which compares two strings. It takes two strings as input
parameter and decides which one is lexicographically larger or smaller: If the first string is greater then
it returns a positive value, if the second string is greater it returns a negative value and if two strings
are equal it returns a zero. The code that is used to compare two strings in C/C++ library is shown
below:
Figure: The standard strcmp() code provided for this problem.
The number of comparisons required to compare two strings in strcmp() function is never returned
by the function. But for this problem you will have to do just that at a larger scale. strcmp() function
continues to compare characters in the same position of the two strings until two different characters
are found or both strings come to an end. Of course it assumes that last character of a string is a null
(‘\0’) character. For example the table below shows what happens when “than” and “that”; “therE”
and “the” are compared using strcmp() function. To understand how 7 comparisons are needed in
both cases please consult the code block given above.
Input
The input file contains maximum 10 sets of inputs. The description of each set is given below:
Each set starts with an integer N (0 < N < 4001) which denotes the total number of strings. Each
of the next N lines contains one string. Strings contain only alphanumerals (‘0’...‘9’, ‘A’...‘Z’, ‘a’...‘z’)
have a maximum length of 1000, and a minimum length of 1.
Input is terminated by a line containing a single zero.
Output
For each set of input produce one line of output. This line contains the serial of output followed by an
integer T. This T denotes the total number of comparisons that are required in the strcmp() function ifUniversidad de Valladolid OJ: 11732 – “strcmp()” Anyone? 2/2
all the strings are compared with one another exactly once. So for N strings the function strcmp() will
be called exactly N(N−1)
2
times. You have to calculate total number of comparisons inside the strcmp()
function in those N(N−1)
2
calls. You can assume that the value of T will fit safely in a 64-bit signed
integer. Please note that the most straightforward solution (Worst Case Complexity O(N2 ∗ 1000)) will
time out for this problem.
Sample Input
2
a
b
4
cat
hat
mat
sir
0
Sample Output
Case 1: 1
Case 2: 6



题目大意:给出N个字符串(包含数字,字母),两两之间调用strcmp()相互比较,问字符比较的总次数.


int strcmp(char* s, char* t){
    int i;
    for(i = 0; s[i] == t[i]; i++)
        if(s[i] == '\0')
            return 0;
    return s[i] - t[i];
}


思路:这里s[i] == t[i] 与 s[i] == '\0' 各有一次比较,所以相同的时候要比较两次,而如果s[i] != t[i]则只要比较一次.

那么就有ans += 现在与当前字符相同的字符串的个数*2 + 字符串总数- 现在与当前字符相同的字符串的个数(这个可以化简的我这里没有化简).

为了对应该公式,直接将Trie树的val值变成经过改点的字符串的个数就行,那么该节点需要比较的次数为2*val[u] + sum - val[u];

而且只要比较n*(n-1)/2次,那么每次插入一个字符串时,同时将它与前面的数比较就行.


相应代码:


#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;

const int sig_size = 64;
const int maxnode = 4000*1000 + 100;

long long ans;
int sum;

struct Trie{
    int ch[maxnode][sig_size];
    int val[maxnode];
    int sz;
    Trie(){
        sz = 1;
        memset(ch[0], 0, sizeof(ch));
        memset(val, 0, sizeof(val));
    }
    int idx(char c){
        if(c == '\0') return 26;
        if(c <= '9' && c >= '0') return c-'0' + 27;
        if(c <= 'z' && c >= 'a') return c-'a';
        if(c <= 'Z' && c >= 'A') return c-'A'+37;
    }
    void clear(){
        sz = 1;
        memset(ch[0], 0, sizeof(ch));
        memset(val, 0, sizeof(val));
    }
    void insert(char* s, int v = 1){
        int u = 0, n = strlen(s);
        int pre = sum-1;
        for(int i = 0; i <= n; i++){
            int c = idx(s[i]);
            if(!ch[u][c]){
                memset(ch[sz], 0, sizeof(ch[sz]));
                val[sz] = 0;
                ch[u][c] = sz++;
            }
            u = ch[u][c];
            ans += val[u]*2;
            ans += pre - val[u];
            pre = val[u];
            val[u] += v;
        }
    }
    bool search(char* s, int len){
        int u = 0;
        for(int i = 0; i < len; i++){
            int c = idx(s[i]);
            if(!ch[u][c]) return false;
            u = ch[u][c];
        }
        if(val[u]) return true;
        else return false;
    }
};

Trie T;

int main(){
    int n, cas = 1;
    char s[1005];
    while(~scanf("%d", &n)){
        if(n == 0) break;
        ans = sum = 0;
        T.clear();
        for(int i = 0; i < n; i++){
            sum++;
            scanf("%s", s);
            T.insert(s);
        }
        printf("Case %d: %lld\n",cas++, ans);
    }
    return 0;
}


是的,C++中确实有`strcmp`函数。`strcmp`是一个字符串比较函数,用于比较两个字符串是否相等。它是在C++标准库中的`<cstring>`(在C++11及以后的版本中,这个库通常被重命名为`<string>`)中定义的。 函数的原型通常如下: ```cpp int strcmp(const char *str1, const char *str2); ``` 这个函数会返回一个整数,如果`str1`和`str2`完全相同,它会返回0。如果`str1`在字典序上小于`str2`,它会返回一个负数。如果`str1`在字典序上大于`str2`,它会返回一个正数。 使用这个函数时,需要注意以下几点: * 字符串必须以空字符('\0')结尾,否则可能会产生未定义的行为。 * 字符串必须以空字符结尾的相同方式进行比较。否则可能会得到错误的结果。 * 两个字符串的指针参数不能是NULL,否则会抛出运行时错误。 使用这个函数的一个例子可能是这样的: ```cpp #include <cstring> #include <iostream> int main() { std::string str1 = "Hello"; std::string str2 = "Hello"; int result = strcmp(str1.c_str(), str2.c_str()); if (result == 0) { std::cout << "Strings are equal." << std::endl; } else if (result < 0) { std::cout << "String1 is less than String2." << std::endl; } else { std::cout << "String1 is greater than String2." << std::endl; } return 0; } ``` 这个程序将打印出 "Strings are equal.",因为两个字符串是相同的。请注意,为了安全起见,最好始终使用字符串的`.c_str()`方法来获取C风格的字符串,以便在需要使用`strcmp`或类似函数的情况下使用它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值