HDU 5495 LCS

Problem Description

You are given two sequence {a_1, a_2, ..., a_n}{a1,a2,...,an} and {b_1,b_2, ... ,b_n}{b1,b2,...,bn}. Both sequences are permutation of {1,2,...,n}{1,2,...,n}. You are going to find another permutation {p_1,p_2,...,p_n}{p1,p2,...,pn} such that the length of LCS (longest common subsequence) of {a_{p_1},a_{p_2},...,a_{p_n}}{ap1,ap2,...,apn} and {b_{p_1},b_{p_2},...,b_{p_n}}{bp1,bp2,...,bpn} is maximum.

Input

There are multiple test cases. The first line of input contains an integer TT, indicating the number of test cases. For each test case:

The first line contains an integer n (1 \le n \le 10^5)n(1n105) - the length of the permutation. The second line contains nn integers a_1,a_2,...,a_na1,a2,...,an. The third line contains nn integers b_1,b_2,...,b_nb1,b2,...,bn.

The sum of nn in the test cases will not exceed 2 \times 10^62×106.

Output

For each test case, output the maximum length of LCS.

Sample Input
2
3
1 2 3
3 2 1
6
1 5 3 2 6 4
3 6 2 4 5 1
Sample Output
2

4

找到循环个数即可

#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;
const int maxn = 300005;
const LL base = 1e9 + 7;
int T, n, m, a[maxn], b[maxn], f[maxn], ans;

int main()
{
    while (cin >> T)
    {
        while (T--)
        {
            scanf("%d", &n);    ans = 0;
            for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
            for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
            for (int i = 1; i <= n; i++) f[a[i]] = b[i];
            for (int i = 1; i <= n; i++)
            if (f[i])
            {
                if (f[i] == i) { ans++; continue; }
                for (int j = f[i], k = j; j != i; )
                {
                    k = j;
                    ans++;
                    j = f[j];
                    f[k] = 0;
                }
                f[i] = 0;
            }
            printf("%d\n", ans);
        }
    }
    return 0;
}


你可能感兴趣的:(HDU,----组合数学)