Codeforces520C_快速幂

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36294146/article/details/84337286

题意:

给出一个01串,每次询问区间[l,r][l,r] 每次可以将区间内一个数取出,并且答案加上这个数的值,区间内剩余的数也加上这个值,求如何安排取出顺序使得答案最大。

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

#define ll long long
#define N 100011
const ll MOD = (ll)1e9 + 7;
int n, q, a[N];

ll qmod(ll base, ll n)
{
    ll res = 1;
    while (n)
    {
        if (n & 1) res = res * base % MOD;
        base = base * base % MOD;
        n >>= 1;
    }
    return res;
}

int main()
{
    while (scanf("%d%d", &n, &q) != EOF)
    {
        a[0] = 0;
        for (int i = 1; i <= n; ++i) scanf("%1d", a + i), a[i] += a[i - 1];
        for (int i = 1, l, r; i <= q; ++i) 
        {
            scanf("%d%d", &l, &r);
            int x = a[r] - a[l - 1], y = (r - l + 1) - x;
            if (x == 0) 
            {
                puts("0");
                continue;
            }
            printf("%lld\n", qmod(2, y) * (qmod(2, x) - 1 + MOD) % MOD);
        }
    }
    return 0;
}

///********///

分割线:

另解:思路:显然我们把所有1都取完,在取0之后会得到更优的解,其实是我们取最大值会比较优。之后我们会发现如果是一个满区间的1的话,那么值就是1 + 2 + 4 。。。等于2^n - 1 ,那么推广到有0的情况,那么的话我们把0也当作1,之后加完一通操作之后的话,我们会发现他其实多算了有多少个1的情况,最后得到的答案其实就是qpow(2,r-l+1) - qpow(2,r - l + 1 - (nex[r] - nex[l-1]));
--------------------- 
 

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000 + 10;
const int MOD = 1e9 + 7;
char ch[maxn];
int nex[maxn];
long long qpow(long long a,long long b)
{
	long long ans = 1;
	while(b)
	{
		if(b&1) ans = ans * a % MOD;
		a = a * a % MOD;
		b = b / 2;
	}
	return ans ;
}
int main()
{
	int n , m;
	scanf("%d%d",&n,&m);
	scanf("%s",ch+1);
	int len = strlen(ch+1);
	for(int i = 1 ; i <= len ; i++) nex[i] = nex[i-1] + (ch[i] == '1' ? 1 : 0);
	while(m--)
	{
		int l , r;
		scanf("%d%d",&l,&r);
		long long ans = qpow(2,r-l+1) - qpow(2,r - l + 1 - (nex[r] - nex[l-1]));
		printf("%lld\n",(ans+MOD)%MOD); 
	}
}

猜你喜欢

转载自blog.csdn.net/qq_36294146/article/details/84337286