Problem.A 二进制数
思路
本题不难,回想十进制转二进制的过程即可,个人认为也可用栈来做
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20000
unsigned int remain_arr[MAXSIZE];
int main() {
unsigned int num_d; //十进制数
unsigned int remain; //余数
unsigned int quo; //商
int bits; //位数
int T;
scanf("%d", &T);
while (T--) {
scanf("%d", &num_d);
bits = -1;
quo = num_d;
if (num_d != 0) {
while (quo != 0) {
remain = quo % 2;
remain_arr[++bits] = remain;
quo /= 2;
}
while (bits >= 0) {
printf("%u", remain_arr[bits--]);
}
}
else
printf("0");
printf("\n");
}
return 0;
}
链接:北邮OJ_二进制数
Problem.B 矩阵幂
思路
要用一个二维数组暂存矩阵,不然在计算过程中矩阵中元素会变化,这样就无法计算,建议画一个3*3矩阵自己算一下找到矩阵乘法中的变量变化情况,相乘的元素的列数总是等于被乘元素的行数,设为m,可以根据m设置循环
#include<stdio.h>
#include<stdlib.h>
int main() {
int n, k;
int i, j, m;
int matrix[10][10];
int res[10][10];
int tmp[10][10];
int pij;
int T;
scanf("%d", &T);
while (T--) {
while (scanf("%d %d", &n, &k) != EOF) {
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
res[i][j] = matrix[i][j];
tmp[i][j] = res[i][j];
}
while (k > 1) {
k--;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
pij = 0;
for (m = 0; m < n; m++) {
pij += (tmp[i][m] * matrix[m][j]);
}
res[i][j] = pij;//如果不设置tmp,用res和matrix相乘,乘的时候res会变,显然不能不设置tmp
}
}
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
tmp[i][j] = res[i][j];//更新
}
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
if (j != n - 1)
printf("%d ", res[i][j]);
else
printf("%d\n", res[i][j]);
}
}
}
return 0;
}
链接:北邮OJ_矩阵幂
Problem.C 二叉排序树
思路
本题比较简单,构造树,编写函数来提高代码简洁性,但要注意新创建一个树结点的时候要将其左右子树置NULL否则会报错
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Treenode
{
int value;
Treenode *left, *right;
}Tree;
Treenode *Insert(Treenode *root, int data);
Treenode *Insert(Treenode *root, int data) {
Treenode *p = root;
Treenode *parent = root;
int flag=-1;
while (p != NULL) {
parent = p;
if (p->value < data) {
p = p->left;
flag = 0;
}
else {
p = p->right;
flag = 1;
}
}
p = (Treenode *)malloc(sizeof(Treenode));
p->left = NULL;
p->right = NULL;
if (flag == 0) {
parent->left = p;
cout << parent->value << endl;
}
else if (flag == 1) {
parent->right = p;
cout << parent->value << endl;
}
else {
root = p;
cout << "-1" << endl;
}
p->value = data;
return root; //返回树的根节点
}
int main() {
int N;
int data;
Treenode *T = NULL;
cin >> N;
while (N--) {
cin >> data;
T=Insert(T, data);
}
return 0;
}
链接:北邮OJ_寻找宝藏
Problem.D IP数据包解析
思路
直接放弃,我的水平做到这一题时间应该也到了(而且这个题也没图,不想看)
链接:北邮OJ_IP数据包解析