HDU - 5514 Frogs(容斥原理)
题意:有n只青蛙,每只青蛙的弹跳能力为ai,他们都从0出发,绕着m个石头围成的圈子跳跃,石头编号为0~m-1,问能被跳到的石头编号之和。
分析:
1、弹跳能力为ai的青蛙,可以跳到的石头编号是gcd(ai, m)的倍数。
2、枚举m的因子,若某个青蛙可以弹跳的石头编号中有该因子,那证明编号为这个因子的石头一定会被跳到,vis[i] = 1。
3、num[i]记录编号为i的石头被跳了几次,如果被跳的次数不等于应跳的次数,则减去多余的影响。---容斥原理
#include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define lowbit(x) (x & (-x)) const double eps = 1e-8; inline int dcmp(double a, double b){ if(fabs(a - b) < eps) return 0; return a > b ? 1 : -1; } typedef long long LL; typedef unsigned long long ULL; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const LL LL_INF = 0x3f3f3f3f3f3f3f3f; const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const int MAXN = 10000 + 10; const int MAXT = 10000 + 10; using namespace std; int gcd(int a, int b){ return !b ? a : gcd(b, a % b); } int a[110]; int vis[MAXN]; int num[MAXN]; int main(){ int T; scanf("%d", &T); int kase = 0; while(T--){ memset(a, 0, sizeof a); memset(vis, 0, sizeof vis); memset(num, 0, sizeof num); int n, m; scanf("%d%d", &n, &m); int tmp = (int)sqrt(double(m)); int cnt = 0; for(int i = 1; i <= tmp; ++i){ if(m % i == 0){ a[cnt++] = i; if(i * i != m){ a[cnt++] = m / i; } } } sort(a, a + cnt); int x; for(int i = 1; i <= n; ++i){ scanf("%d", &x); int t = gcd(x, m); for(int j = 0; j < cnt; ++j){ if(a[j] % t == 0) vis[j] = 1; } } LL ans = 0; for(int i = 0; i < cnt - 1; ++i){ if(vis[i] != num[i]){ int t = (m - 1) / a[i]; ans += (LL)t * (t + 1) / 2 * a[i] * (vis[i] - num[i]); t = vis[i] - num[i]; for(int j = i; j < cnt - 1; ++j){ if(a[j] % a[i] == 0){ num[j] += t; } } } } printf("Case #%d: %lld\n", ++kase, ans); } return 0; }