码迷,mamicode.com
首页 > 其他好文 > 详细

HDU4407Sum 容斥定理

时间:2015-05-29 12:07:05      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4407

题意:在1E5个数中求某段区间中和p互素的数和。有1000次操作,每次操作可能是询问,可能是修改单点值。

注意!!初始时,序列是1,2.....n,很关键呀。操作数很少,可以用map存下修改操作,每次询问求cal(r,p)-cal(l-1,p),在加上修改的影响。

cal(r,p)可用容斥求得。


代码:

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

Problem : 4407 ( Sum )
Judge Status : Accepted
Language : G++
Author : alpc_wt

********************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>
#include<cmath>
using namespace std;
typedef long long ll;

const int N = 4*100000+10;
const int maxn = 4*100000;

vector<int> pri[N];
map<int,int> mm;
map<int,int>::iterator it;
int cnt[N];

void init(){
    for(int i=0;i<=maxn;i++)
        pri[i].clear();
    for(int i=2;i<=maxn;i++) if(pri[i].size()==0)
        for(int j=i;j<=maxn;j+=i)
            pri[j].push_back(i);
}


int sav[N][2],num;

ll cal(int r,int p){
    if(r==0) return 0;
    ll ret = 0;

    int size = pri[p].size();
    for(int i=0;i<(1<<size);i++){
        int z=1 , fl =1;
        for(int j=0;j<size;j++)
            if(i&(1<<j)){
                z *= pri[p][j];
                fl *= -1;
            }
        ll co = r / z;
        ll tmp = co * (co+1) * z / 2;

        if(fl==1) ret += tmp;
        else ret -= tmp;
    }
    return ret;
}

ll solve(int l,int r,int p){
    ll ans = cal(r,p) - cal(l-1,p);
    for(it=mm.begin();it!=mm.end();it++){
        int x = it->first;
        int y = it->second;
        if(x<l || x>r) continue;
        if(__gcd(x,p)==1) ans -= x;
        if(__gcd(y,p)==1) ans += y;
    }
    return ans;
}

int main(){
    int T,n,m,p,c,x,l,r;
    init();
    cin >> T;
    while(T--){

        scanf("%d%d",&n,&m);
        num=0;
        mm.clear();

        for(int i=1;i<=m;i++){
            scanf("%d",&x);
            if(x==1){
                scanf("%d%d%d",&l,&r,&p);
                ll ans = solve(l,r,p);
                printf("%lld\n",ans);
            }
            else{
                scanf("%d%d",&x,&c);
                mm[x] = c;
            }
        }
    }
    return 0;
}


HDU4407Sum 容斥定理

标签:

原文地址:http://blog.csdn.net/alpc_wt/article/details/46226187

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!