suxxsfe

一言(ヒトコト)

ds3

2024 09 25
hw3

1

C

2.5

1

AD

2

int check(char *str){
  int sum = 0;
  for(char *c=str; *c; c = c+1){
    if(*c == 'I'){
      sum = sum+1;
    }
    else{
      sum = sum-1;
    }
    if(sum < 0){
      return false;
    }
  }
  return true;
}

2.9

1

int getAck(int m, int n){
  if(m == 0){
    return n+1;
  }
  else if(n == 0){
    return getAck(m-1, 1);
  }
  return getAck(m-1, getAck(m, n-1));
}

计算 Ack(2,1) 的过程:

Ack(2,1) ---- 5
  Ack(2,0) ---- 3
    Ack(1,1) ---- 3
      Ack(1,0) ---- 2
        Ack(0,1) ---- 2
      Ack(0,2) ---- 3
  Ack(1,3) ---- 5
    Ack(1,2) ---- 4
      Ack(1,1) ---- 3
      Ack(0,3) ---- 4
    Ack(0,4) ---- 5

2

int getAck(int m, int n){
  int stack[MAX], top;
  stack[1].m = m;
  stack[1].n = n;
  top = 1;
  while(s[top].m != 0){
    while(s[top].m){
      while(s[top].n){
        s[top+1].m = s[top].m;
        s[top+1].n = s[top].n-1;
        top = top+1;
      }
      s[top].m = s[top].m-1;
      s[top].n = 1;
    }
    if(top != 0){
      s[top-1].m = s[top-1].m-1;
      s[top-1].n = s[top].n+1;
      top = top-1;
    }
  }
  return s[top].n+1;
}

2.10

int getMax(Node *f){
  if(f->next == NULL){
    return f->val;
  }
  int next = getMax(f->next);
  return next>f->val ? next : f->val;
}

int getNum(Node *f){
  if(f == NULL){
    return 0;
  }
  return 1+getNum(f->next);
}

double getAvg(Node *f, int *num = NULL){
  if(f->next == NULL){
    if(num != NULL){
      *num = 1;
    }
    return f->val;
  }
  int n;
  double avg = getAvg(f->next, &n);
  if(num != NULL){
    num = n+1;
  }
  return ((avg*n)+f->val)/(n+1);
}

补充题

int type[10];
void find(int pos = 1,int lastNum = 0, int lastOp = 1, int sum = 0){
  if(pos == 9){
    sum = sum+lastNum*lastOp;
    if(sum != 110){
      return;
    }
    for(int i = 1; i < 10; i = i+1){
      printf("%d", i);
      if(type[i] == 1){
        putchar('+');
      }
      else{
        putchar('-');
      }
    }
    puts("");
    return;
  }
  
  type[i] = 0;
  find(pos+1, lastNum*10+i, lastOp, sum);
  type[i] = 1;
  find(pos+1, 0, 1, sum+lastNum*lastOp);
  type[i] = -1;
  find(pos+1, 0, -1, sum+lastNum*lastOp);
}
posted @ 2024-09-25 23:09  suxxsfe  阅读(49)  评论(0编辑  收藏  举报