约瑟夫问题——环形链表的基本使用操作;大整数加法——数组的基本运用;

版权声明:禁止copy抄袭,博主很凶的哦,超级凶的那种哦。 https://blog.csdn.net/Strawberry_595/article/details/82939138

完成以下程序,并在右边空白处,对错误进行修改,并记录下程序运行结果:

 

1.约瑟夫问题

描述:有n只猴子,按顺时针方向围成一圈选大王(编号从1到n),从第1号开始报数,一直数到m,数到m的猴子退出圈外,剩下的猴子再接着从1开始报数。就这样,直到圈内只剩下一只猴子时,这个猴子就是猴王,编程求输入n,m后,输出最后猴王的编号。

输入:输入包含两个整数,第一个是n,第二个是m (0 < m,n <=300)。

输出:输出包含一行,即最后猴王的编号。

 

 

#include <cstdio>

#include <cmath>

#include <algorithm>

#include <iostream>

 

using namespace std;

 

struct node

{

    int data;

    node *next;

};

 

int main()

{

    int n,m;

 

    while(cin >> n >> m && n)

    {

    node *first;

    node *p,*q;

    first = new node;

    first->data = 1;

    first->next = first;

    if(m != 1){

    for(int i = n;i >= 2;i--){  //倒序插入n个数据

        p = new node;

        p->data = i;

        p->next = first->next;

        first->next = p;

    }

    q = first;

    while(q->next != q){  //删除第'm'个元素

        n = m - 1;

        while(n--){

            q = q->next;

        }

        p = q->next;

        q->next = p->next;

        delete p;

        q = q->next;

    }

    cout << q->data << endl;

    }

    else

        cout << n << endl;

    while(first->next != first){  //清空链表

        q = first;

        first = first->next;

        delete q;

    }

    delete first;

    }

}

 

 

 

 

2.大整数加法

描述:求两个不超过200位的非负整数的和。

输入:有两行,每行是一个不超过200位的非负整数,可能有多余的前导0。

输出:一行,即相加后的结果。结果里不能有多余的前导0,即如果结果是342,那么就不能输出为0342。

#include <cstdio>

#include <cmath>

#include <algorithm>

#include <iostream>

#include <cstring>

#include <string>

#include <stack>

#include <queue>

 

using namespace std;

 

 

char a[205], b[205];

int c[205], d[205];

long long sum;

int he;

int main()

{

      scanf("%s %s", a + 1, b + 1);

      int lena = strlen(a + 1);

      int lenb = strlen(b + 1);

      int MaxLen = max(lena, lenb);

      he = 0;

      queue <int> cc;

 

      for(int i = 1;i <= lena;i++){

        c[lena - i + 1] = a[i] - '0';

      //    cout << a[i];

      }

      //cout << endl;

      for(int i = 1;i <= lenb;i++){

        d[lenb - i + 1] = b[i] - '0';

      //    cout << b[i];

      }

      //cout << endl;

      for(int k = 1;k <= MaxLen;k++){

        he = c[k] + d[k];

        if(he > 9){

            c[k + 1] += (he / 10);

            he = he % 10;

        }

        cc.push(he);

      }

      int e = 1;

 

      while(!cc.empty())

      {

        int y = cc.front();

        sum += (y * e);

        e *= 10;

        cc.pop();

      }

      cout << sum << endl;

      return 0;

}

 

 

 

 

 

样例输入

12 4

样例输出

1

 

 

 

 

 

 

 

 

 

样例输入

22222222222222222222

33333333333333333333

样例输出

55555555555555555555

 

猜你喜欢

转载自blog.csdn.net/Strawberry_595/article/details/82939138