容斥原理(模版 ZOJ 2836)

import java.io.*;
import java.util.*;
import java.math.*;

public class Main {

long m, ans;
int n, a[];

long GCD(long a, long b) {  // 中间结果用long保险,下LCM同
return b == 0 ? a : GCD(b, a % b);
}

long LCM(long a, long b) { 
return a / GCD(a, b) * b;
}

void dfs(long temp, int st, int count) {
temp = LCM(temp, a[st]); //求元素前面几个数的最小公倍数
if ((count & 1) != 0) ans += m / temp;
else ans -= m / temp; //这里减去前面重复的数,是精华所在
for (int i = st + 1; i < n; i++)
dfs(temp, i, count + 1);
}

void run() {
while (cin.hasNext()) {
n = cin.nextInt();
m = cin.nextInt();
a = new int[n];
for (int i = 0; i < n; i++)
a[i] = cin.nextInt();
ans = 0;
for (int i = 0; i < n; i++)
dfs(a[i], i, 1);
System.out.println(ans);
}
}

public static void main(String[] args) {
Main solved = new Main();
solved.run();
}

// static InputStream inputStream = System.in;
// static InputReader cin = new InputReader(inputStream);

Scanner cin = new Scanner(new BufferedInputStream(System.in));

}


class InputReader {

private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;

public InputReader(InputStream stream) {
this.stream = stream;
}

public int read() {
if (numChars == -1)
return -1;
//throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}

public int nextInt() {
int c = read();
if (c == -1)
return -1;
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}

public String next() {
StringBuilder str = new StringBuilder();
int ch;
while (isSpaceChar(ch = read()));
if (ch == -1)
return null;
do {
str.appendCodePoint(ch);
} while (!isSpaceChar(ch = read()));
return str.toString();
}

public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}

public char nextCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}

}

posted on 2013-02-19 20:04  Sure_Yi  阅读(198)  评论(0编辑  收藏  举报

导航