(水题)洛谷

https://www.luogu.org/problemnew/show/P1308

简单哈希一下判断,练练手。

注意fgets()的用法,第一个参数传存储位置,第二个参数传内存上限,第三个传stdin。

注意scanf()任何东西(包括%s)都是会把换行符留在输入流中,这时候可以用getchar()跳过它。

sscanf()好像和想象中不太一样?

C语言的字符拥有isupper(),islower(),isalpha(),isdigit(),isalnum()等函数,且可以用toupper(char),tolower(char)来快速转换。

#include<bits/stdc++.h>
using namespace std;
#define ll long long

char s[15];
char t[1000005];
char tmp[1000005];
int tmptop=0;
int s1,t1;
ll hash_s;

ll hash_f(char* s,int l){
    ll ha=0;
    for(int i=0;i<l;i++){
        ha=ha*23333+s[i];
    }
    return ha;
}

int main(){
    scanf("%s",s);
    getchar();
    fgets(t,1000005,stdin);

    s1=strlen(s);
    for(int i=0;i<s1;i++){
        if(s[i]>='A'&&s[i]<='Z'){
            s[i]=s[i]-'A'+'a';
        }
    }

    hash_s=hash_f(s,s1);
    //cout<<hash_s<<endl;

    int ans=0;
    int first=-1;
    int be=0;

    int i=0;
    while(t[i]==' '||isalpha(t[i])){
        //cout<<t[i]<<endl;
        if(t[i]==' '){
            tmp[tmptop]='
';
            ll hares=hash_f(tmp,tmptop);
            if(hares==hash_s){
                ans++;
                if(first==-1)
                    first=be;
            }
            tmptop=0;
            be=i+1;
        }
        else{
            tmp[tmptop]=tolower(t[i]);
            tmptop++;
        }
        i++;
    }

    if(first==-1)
        printf("-1
");
    else
        printf("%d %d
",ans,first);

}
原文地址:https://www.cnblogs.com/Yinku/p/10293818.html