[Algorithm] - inclusion and exclusion

Inclusion-exclusion principle

The basic idea: FIG here as example take it
Here Insert Picture Description
that we know the number of data set A, B, C, and would like to obtain the size A∩B∩C
1. We first determined the size of the A + B + C, but at this time 2, 4, 6 of the two regions is calculated, the calculated area 5 3
2. Therefore, we should be calculated by subtracting the plurality
A∩B∩C = a + B + C - B∩C - A∩C - A∩ B (zone 5 at this time has been calculated by subtracting three times three times) + A∩B∩C (region 5 should be added last)

Examples MDL Gugu Gu

Title Description

After the last MDL hire kids to help her take items, the commission has not (candy) to kids. This put the kids anxious. In order to get back the candy, the kids decided to go gank wave of MDL, MDL is also very embarrassed.
But MDL could not pay any candy, so decided to hide for a while, desperation, decided to bring their children 10 ^ 9 small partners to gank MDL.
Then MDL junior partner MJJ said: "MDL Mo panic, I've got three magic dove, respectively, on top of a prime number, so that number can be divisible numbers above people into pigeon, so that you can greatly reduce their numbers ! "(10 ^ 9 carried by individual kids are numbered from 1 to 10 ^ 9), but because of all of the children can not become a dove, MDL manpower needed to prepare?

Input

The first line contains a positive integer T (T <200 is),
T line after each line contains three positive integers, a, b, c (2 <= a, b, c <106;! A = b, b! ! = c, c = a; guarantee a, b, c is a prime number),
they represent the three magic numbers of pigeons.

Output

Corresponding to each of the output level of interest MDL number of the number of row for each result.
C language code

#include <stdio.h>
#include <math.h> //pow函数的头文件

int main(void)
{
    int t, ans, sum, a, b, c;//ans用于统计变成鸽子的数目,sum为全体小朋友,ans-sum即为所求
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d%d", &a, &b, &c);
        ans = 0, sum = pow(10, 9);
        ans += sum/a,ans += sum/b, ans += sum/c;//ans用于统计a, b, c倍数的个数,相当于算法中A+B+C的数量
        ans -= sum/(a*b), ans -= sum/(a*c), ans -= sum/(b*c);//ans此时相当于算法中A+B+C - B∩C - A∩C - A∩B
        ans += sum/(a*b*c);//ans相当于算法中A+B+C - B∩C - A∩C - A∩B + A∩B∩C 也就是变成鸽子的数量
        printf("%d\n", sum-ans);
    }
    return 0;
}

Published 20 original articles · won praise 2 · Views 946

Guess you like

Origin blog.csdn.net/zhbbbbbb/article/details/103428890