gym/100482/problem/G Pairs【逆元】

G. Pairs

The pair in the land of 1000000007 is the pair of numbers a and b with the following relation: a × b = 1 (mod 1000000007). It is believed to be the sign of divine. Your task is to increase the number of happy marriages so you must find the maximum number of distinct pairs! Distinct pairs can not have the same number (with the same index). Pairs are different when the sets of their indices are different

Input

The first line contains the number of test cases T (T ≤ 5). The first line of each test case contains the size of population, n (1 ≤ n ≤ 30000). The following n lines contain the numbers ai (1 ≤ ai < 1000000007).

Output

For each test case output one line containing “Case #tc: num”, where tc is the number of the test case (starting from 1) and num is the maximum number of distinct pairs.

Examples

Input

1
5
1
1
1
2
500000004

Output

Case #1: 2


题意:

有n个数,只有满足 a×b%1000000007=1 a × b % 1000000007 = 1 的两个数可以凑成一对,每个数只能属于一个对,最多能组多少对
输入每个数 0<ai<1000000007 0 < a i < 1000000007


解:

移项可得

a×b%1000000007=1a=b1a=inv(b) a × b % 1000000007 = 1 a = b − 1 a = i n v ( b )

只要两个数互为逆元即可,用map统计所有数的数量,对于每个数都看有几个数是它的逆元

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<map>
using namespace std;
typedef long long LL;
const LL mod = 1000000007;
LL quick_mod(LL a, LL b)
{
    LL base = a;
    LL ans = 1;
    while (b)
    {
        if (b & 1)
        {
            ans *= base;
            ans %= mod;
        }
        base *= base;
        base %= mod;
        b >>= 1;
    }
    return ans % mod;
}
LL a[100000];
map<LL, LL>mp;
int main()
{
    int T;
    scanf("%d", &T);
    for (int tc = 1; tc <= T; tc++)
    {
        int n;
        mp.clear();
        scanf("%d", &n);
        for (int i = 0; i < n; i++)
        {
            scanf("%lld", &a[i]);
            mp[a[i]]++;
        }
        LL ans = 0;
        for (int i = 0; i < n; i++)
        {
            LL inv = quick_mod(a[i], mod - 2) % mod;
            if (inv == 1)
            {
                ans += mp[a[i]] / 2;
                mp[a[i]] = 0;
            }
            else
            {
                int t = min(mp[a[i]], mp[inv]);
                ans += t;
                mp[a[i]] -= t;
                mp[inv] -= t;
            }
        }
        printf("Case #%d: %lld\n", tc, ans);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值