sdnu oj 1579 FFFFFunctions

在这里插入图片描述
emmm…这个函数原来是求最大公因数啊, 没转弯直接照写 WA 了
然后,这是第二个函数
在这里插入图片描述
题目描述
Now, you are given two sequences:
在这里插入图片描述
and
在这里插入图片描述
You are supposed to calculate the value of the function 2.

Input
The input contains several test cases and the number of test cases is no more than 500.
For each test case, the first line contains a interger n. The second line contains n intergers for the sequence a. The third line contains n intergers for the sequence p which is a permutation for {1,2,3,…,n}.
(1<=n<=1000000, 1<=ai<=1000000000, 1<=pi<=n)
hint: while n is 0,you should output nothing and input next case

Output
For each test case, output a interger in one line for the value of the function 2.

Sample Input
2
3 5
2 1
Sample Output
1

#include 
#include 
#include 
#include 
#include 
#define N 1000006
using namespace std;
typedef long long ll;

int a[N], p[N];

int func1(int a, int b)
{
    return b ? func1(b, a%b) : a;
}

int func2(int n)
{
    if(n == 2)
        return func1(a[p[1]], a[p[2]]);
    return func1(func2(n-1), a[p[n]]);   //多直白的递归,跟题干描述一样
}
int main()
{
    int n, i;
    while(~scanf("%d", &n))
    {
        memset(a, 0, sizeof a);
        memset(p, 0, sizeof p);
        for(i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        for(i = 1; i <= n; i++)
            scanf("%d", &p[i]);
        printf("%d\n", func2(n));
    }
    return 0;
}

你可能感兴趣的:(oj)