奋战杭电ACM(DAY1)

    今天开始刷杭电ACM的题库,我是一只小笨鸟,只有勤奋才能飞得高,前辈的指点少而精,我会全部做到!

    今天刷了4道题……是不是很少……不过我会努力的,赶上赶上!

A + B Problem
#include <iostream>
using namespace std;
void main()
{
    int a,b;
    while(cin >> a >> b)
        cout << a+b << endl;
}

Sum Problem

#include <iostream>
using namespace std;
void main()
{
    int n,i,sum;

    while(cin >> n)
    {    
        sum=0;
        for(i=1;i<=n;i++)
            sum +=i;
        cout << sum << '
' << endl;
    }
}

A + B Problem II

#include <iostream>
#include <string>
using namespace std;
string addstring(string a, string b)
{
    string c="";
    int i,j,tmp;
    i=a.length()-1;
    j=b.length()-1;
    tmp=0;
    while(i>=0 || j>=0)
    {
        if(i>=0 && j>=0)
            tmp += a[i]-'0'+b[j]-'0';
        else if(i>=0 && j<0)
            tmp += a[i]-'0';
        else if(i<0 && j>=0)
            tmp += b[j]-'0';
        c = (char)((tmp%10)+'0') + c;
        tmp /=10;
        i--;
        j--;
    }
    return c;
}
int main()
{
    int T,i;
    string A,B,C;
    cin >> T;
    for(i=1; i<=T; i++)
    {
    
        cin >> A >> B;
        C=addstring(A,B);
        if(i>1)
            cout << endl;
        cout << "Case " << i << ":" << endl;
        cout << A << " + " << B << " = " << C  << endl;
    }
    return 0;
}

The 3n + 1 problem

#include <iostream>

using namespace std;

void the3n1Problem();

int main()
{
    the3n1Problem();

    return 0;
}

#define MAXNUM 1000000
int cache[MAXNUM];

int CycleLength(unsigned long n)
{
    if (n <= 1)
        return 1;

    if (n >= MAXNUM)
    {
        int m = 0;
        while(n >= MAXNUM)
        {
            if (n%2 == 0)
                n = n / 2;
            else
                n = 3*n + 1;

            m++;
        }

        return CycleLength(n)+m;
    }

    if (cache[n] == 0)
    {
        if (n%2 == 0)
            cache[n] = CycleLength(n/2)+1; 
        else
            cache[n] = CycleLength(3*n+1)+1;
    }
    
    return cache[n];
}

int MaxCycleLength(int i, int j)
{
    static bool needInit = true;
    int k, m;

    if(i > j)
        return MaxCycleLength(j,i);
    
    if(needInit)
    {
        needInit = false;
        memset(cache,0,sizeof(cache));

        for(k = 1, m = 1; k < MAXNUM; k <<= 1, m++)
            cache[k] = m;
    }

    m = 0;
    for (k = i; k <= j; k++)
    {
        int len = CycleLength(k);
        if (len > m) m = len;
    }

    return m;
}

void the3n1Problem()
{
    int i, j, m;

    while(cin >> i >> j)
    {
        if(i == 0 && j == 0) break;

        m = MaxCycleLength(i,j);

        cout << i << ' ' << j << ' ' << m << endl;
    }
}

  今天就是这么多了,晚上继续刷题!算法还没有掌握,书在路上,这几天快开学了事也多,先自己试着做题吧!加油加油!





原文地址:https://www.cnblogs.com/ques3512012019/p/3295216.html