UVa -- 10324 Zeros and Ones

本文介绍了一种用于判断指定区间内字符是否一致的高效算法。该算法适用于由0和1组成的长度不超过100万的字符串,并能快速响应多个查询请求。通过预处理字符串并使用前缀和技巧,算法能在常数时间内给出查询答案。

Description

Given a string of 0's and 1's up to 1000000 characters long and indices i and j, you are to answer a question whether all characters between position min(i,j) and position max(i,j) (inclusive) are the same.

Input

There are multiple cases on input. The first line of each case gives a string of 0's and 1's. The next line contains a positive integer n giving the number of queries for this case. The next n lines contain queries, one per line. Each query is given by two non-negative integers, i and j. For each query, you are to print Yes if all characters in the string between position min(i,j) and position max(i,j) are the same, and No otherwise.

Output

Each case on output should start with a heading as in the sample below. The input ends with an empty string that is a line containing only the new line character, this string should not be processed. The input may also with end of file. So keep check for both.

<span style="font-size:14px;">#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=1000100;
char f[maxn];
int s[maxn];
int interval_sum(int i, int j){
    if(i>j) swap(i,j);
    if(s[j]-s[i-1]==j-i+1||s[j]-s[i-1]==0)
        printf("Yes\n");
    else printf("No\n");
}
int main(){
    int a,b,n,cnt=0;
    while(scanf("%s",f)==1){
        cnt++;
        memset(s,0,sizeof(s));
        int l=strlen(f);
        s[0]=f[0]-'0';
        for(int i=1;i<l;i++)
            s[i]=s[i-1]+(f[i]-'0');
        printf("Case %d:\n",cnt);
        scanf("%d",&n);
        for(int h=0;h<n;h++){
            scanf("%d%d",&a,&b);
            interval_sum(a,b);
        }
    }
    return 0;
}
</span>
<span style="font-size:14px;">#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=1000100;
char f[maxn];
int main(){
    int a,b,n,cnt=1;
    while(scanf("%s",f)==1){
        printf("Case %d:\n",cnt);
        scanf("%d",&n);
        for(int h=0;h<n;h++){
            scanf("%d%d",&a,&b);
            int temp,flog=0;
            if(a>b) swap(a,b);
            for(int i=a;i<=b;i++){
                if(f[i]!=f[a]){
                    flog=1;
                    break;
                }
            }
            if(flog)
                printf("No\n");
            else printf("Yes\n");
        }
    cnt++;
    }
    return 0;
}</span>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值