1. 程式人生 > >gym/100482/problem/G Pairs【逆元】

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的兩個數可以湊成一對,每個數只能屬於一個對,最多能組多少對
輸入每個數0<ai<1000000007

解:

移項可得

a×b%1000000007=1a=b1a=inv(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); } }