Fraction(递归回溯函数 中 分数的返回)

来源:互联网 发布:everying软件 编辑:程序博客网 时间:2024/05/18 18:15

选自ccpc长春赛:

Fraction

题意:求

思路;递归函数模拟,主要是分数的返回,用一个结构体表示,还有一个需要注意的是记得通分;


#include<bits/stdc++.h>using namespace std;struct Node{    int x;    int y;};//表示分数的结构体int a[100], b[100];int n;Node fun(int x,int y){    if(x == n && y == n)    {        Node temp;        temp.x = b[n];        temp.y = a[n];        return temp;    }    Node temp ;    temp.x = b[x] * fun(x+1,y +1).y;//通分后的分子    temp.y = a[y] * fun(x + 1, y + 1).y + fun(x + 1,y + 1).x;//通分后的分母    return temp;}int gcd(int x,int y){    if(y == 0)        return x;    return gcd(y,x%y);}int main(){    int Tcase;    scanf("%d",&Tcase);    for(int ii = 1; ii <= Tcase ; ii ++)    {        scanf("%d",&n);        for(int i = 1; i <= n ;i ++)        {            scanf("%d",&a[i]);        }        for(int i = 1; i <= n ;i ++)        {            scanf("%d",&b[i]);        }        Node temp = fun(1,1);        int t = gcd(temp.x,temp.y);        cout<< "Case #"<< ii <<": "<< temp.x/t <<" "<<temp.y/t <<endl;    }    return 0;}

下面附上这个比赛写出来的几个题:
Triangle


题意:给出一个n,就是1 ~ n 这 n 个数,然后要删去多少个数才能使得剩下的数不能组成三角形;

思路:找出了规律:1,2,3,5,8,13,。。。。这些数不能删,其他的都要删,大哥表就好了;

#include<bits/stdc++.h>using namespace std;const int maxn = 1000000 + 10;bool is_striangle[maxn];int a[maxn];void Init(){    memset(is_striangle,false,sizeof(is_striangle));    is_striangle[1] = is_striangle[2] = is_striangle[3] = true;    int x = 2,y = 3;    for(int i = x + y ; x + y <= 100 ; i ++)    {        is_striangle[x + y] = true;        int temp = x;        x = y;        y = temp +y;    }    a[1] = 0;    for(int i = 2; i <= 100 ; i ++)    {        if( ! is_striangle[i])            a[i] = a[i - 1] + 1;        else a[i] = a[i - 1];    }//    for(int i = 1; i <= 20 ; i ++)//    {//        cout << i << " " << a[i] <<endl;//    }}int main(){    Init();    int Tcase;    scanf("%d",&Tcase);    for(int ii = 1; ii <= Tcase; ii ++)    {        int n;        scanf("%d",&n);        cout<< "Case #"<< ii <<": "<< a[n] << endl;    }    return 0;}

Sequence I

题意:两个数组,看在a数组中能找到多少个b数组,不过这个要求在a数组中找的时候得按P这个间隔走;

#include<bits/stdc++.h>using namespace std;const int maxn = 1000000 + 10;int n,m,k;int a[maxn], b[maxn];bool solve(int i){    int t = 1,j;    for(j = i ;j <= n && t <= m;j += k)    {        if(a[j] == b[t])        {            t ++;        }        else return false;    }    if(j <= n + k && t == m + 1)    {        return true;    }    else return false;}int main(){    int Tcase;    scanf("%d",&Tcase);    for(int ii = 1; ii <= Tcase ; ii ++)    {        scanf("%d%d%d",&n,&m,&k);        for(int i = 1; i<= n ; i++)            scanf("%d",&a[i]);        for(int i = 1 ;i <= m ;i ++)            scanf("%d",&b[i]);        int ans = 0;        for(int i = 1; i<= n;i ++)        {            if(solve(i))                ans ++;        }        cout <<"Case #"<< ii <<": "<< ans << endl;    }    return 0;}

0 0