题目来自这位博主的回忆【链接】
题目分类:
- 质因数分解:简单模拟
- 二叉树找权:DFS+建树
- 折叠字串 : 区间DP(即使每年考区间DP,但也很难。。。)
1.质因数分解
质因数分解。给一个n,小于1亿,输出它的从小到大的质因数。如:输入6,输出2*3
题解:
由于找不到原题,只能根据回忆去解,找不到什么感觉比较难的点。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
using namespace std;
vector<int> vt;
int main()
{
int n;
scanf("%d",&n);
int tmp=n;
for(int i=2;i<=sqrt(tmp);i++)
while(tmp%i==0)
{
vt.push_back(i);
tmp=tmp/i;
}
vt.push_back(tmp);
for(int i=0;i<vt.size();i++)
printf("%d ",vt[i]);
return 0;
}
2.二叉树算权
二叉树搜索。给一个二叉树(节点数小于等于64,节点值不重复)的前序中序,再给一个整数,输出从根节点到叶子节点路径权值总和等于该数的路径总数。
(这是我写的样例)
输入:
7 10
1 2 4 7 5 3 6
7 4 2 5 1 6 3
输出:
1
题解:
感觉也难度不大,样例我自己写的。19年机试确实是没参考的标准题目,只有别人的回忆。建树+DFS,注意回溯、建树就能做出来。总体专业考察硬核但不算难。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
using namespace std;
vector<int> pre,in,tmppath,res;
int num=0,n,m;
struct node
{
int val;
node* right,*left;
};
node* build(int r,int l,int root)
{
if(r>l) return NULL;
int t=0;
node * tmp = new node();
while(pre[root]!=in[t]) t++;
tmp->left=build(r,t-1,root+1);
tmp->right=build(t+1,l,root+t-r+1);
tmp->val=pre[root];
return tmp;
}
void dfs(node* &root)
{
tmppath.push_back(root->val);
if(root->right==NULL&&root->left==NULL)
{
//叶子节点处理
int cnt=0;
for(int i=0;i<tmppath.size();i++)
cnt+=tmppath[i];
if(m==cnt) num++;
//如果路径内权和==m,则总目标条数+1
tmppath.pop_back();
//printf("%d\n",cnt);
return ;
}
//printf("%d\n",root->val);
if(root->left!=NULL) dfs(root->left);
if(root->right!=NULL) dfs(root->right);
tmppath.pop_back();
return ;
}
int main()
{
scanf("%d %d",&n,&m);
pre.resize(n);
in.resize(n);
for(int i=0;i<n;i++) scanf("%d",&pre[i]);
for(int i=0;i<n;i++) scanf("%d",&in[i]);
node * root=NULL;
root=build(0,n-1,0);
//cout<<root->left->left->left->val<<endl;
dfs(root);
printf("%d\n",num);
return 0;
}
3.折叠字串
给一个字符串(len<=100)
把这个字符串折叠(就是压缩)
记 X(子串) 表示重复 X次该子串
比如 3(orz) orzorzorz
测试样例:
AAAAAAAAAABABABCCD
9(A)3(AB)CCD
NEERCYESYESYESNEERCYESYESYES
2(NEERC3(YES))
题解:讲道理考试的时候,我是写不出来的。。。。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
using namespace std;
int dp[999][999];
string s1,s2;
//计算r-k在k-l里循环的均时重复字符串
int check(int l,int k,int r)
{
if((r-k)%(k-l+1)) return 0;
for(int i=k+1,j=1;i<=r;i++,j++)
{
if(j>k)j=1;
if(s2[i]!=s2[j]) return 0;
}
return 1;
}
//计算数字所占位数
int cal(int t)
{
int ans=0;
while(t!=0)
{
ans++;
t=t/10;
}
return ans;
}
int main()
{
cin>>s2;
for(int i=0;i<s2.size();i++) dp[i][i]=1;
for(int len=2;len<s2.size();len++)
for(int i=0;i+len-1<s2.size();i++)
{
int j=i+len-1;
dp[i][j]=len;
for(int k=i;k<j;k++)
{
dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
if(check(i,k,j))
dp[i][j]=min(dp[i][j],dp[i][k]+2+cal(len/(k-i+1)));
}
}
printf("%d\n",dp[1][s2.size()-1]);
return 0;
}