2022.7.12 练习+dfs、栈习题

本文介绍了如何使用贪心算法解决字符串排序问题,通过拼数游戏实现数字的逐位比较;同时展示了栈在求解回文字符串、单调栈和数列转换中的应用。这些例子揭示了栈在IT面试中的重要性和基本操作技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.登录—专业IT笔试面试备考平台_牛客网

拼数:是一道贪心题目,需要按每一位从左到右数值的大小进行排序,可以用结构体存入数据,然后写一个cmp()函数,用sort()函数进行排序,最后输出结果即可。

 

#include<iostream>
#include <algorithm>
#include <string>
using namespace std;
const int N=25;
struct num{
	string s;
}a[N];
int  cmp(num x,num y){
	int len_x=x.s.size(),len_y=y.s.size();
	if(len_x!=len_y){
		if(len_x>len_y){
			for(int i=len_y;i<len_x;i++){
				y.s+=y.s[len_y-1];
			}
		}
		else {
			for(int i=len_x;i<len_y;i++){
				x.s+=x.s[len_x-1];
			}
		}
	}
	//cout <<x.s<<endl;
	int i;
	for(i=0;i<max(len_x,len_y);i++){
		if(x.s[i]!=y.s[i]) return x.s[i]-'0'>y.s[i]-'0';
	}
    return x.s[i-1]>y.s[i-1];
}
int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++) cin>>a[i].s;
	sort(a,a+n,cmp);
	for(int i=0;i<n;i++){
		cout <<a[i].s;
	}
}

2.登录—专业IT笔试面试备考平台_牛客网

 关键在于求出每个数的每一位,最后相加,然后循环至和为个位即可。

#include<iostream>
#include <algorithm>
#include <string>
#include <cmath>
using namespace std;
const int N=12;
int n;
int a[N];
int main() {
	cin>>n;
	while(n>10) {
		int sum=0;
		a[1]=n%10;
		sum+=a[1];
		for(int i=2; i<=N; i++) {
			int tmp=1;
			for(int j=1;j<i;j++) tmp*=10;
			a[i]=n/tmp%10;
			//cout <<a[i]<<endl;
			sum+=a[i];
		}
		n=sum;
	}
	cout <<n;
}

3.解密回文(栈)

一个很简单的题目,主要是理解栈的思想,另外用两个指针从头和尾循环也可以得出答案。

#include <iostream>
#include <cstring>
#include <string>
using namespace std;
string s;
int main(){
	cin>>s;
	int i,j;
	bool pd=true;
	for(i=0,j=s.size()-1;i<j;i++,j--){
		if(s[i]!=s[j]){
			pd=false;
			break;
		}
	}
	if(pd) cout <<"YES"<<endl;
	else cout <<"NO"<<endl;
}

 4.

 同样是栈,栈内存放的元素都是单调的元素,因此被称为单调栈。

#include <iostream>
#include <algorithm>
using namespace std;
const int N=1e5+10;
int stk[N],tt;
int main() {
	int n;
	cin>>n;
	int i,j;
	while(n--) {
		int x;
		cin>>x;
		if(tt==0) {
			stk[++tt]=x;
			cout <<"-1"<<" ";
		} else {
			while(stk[tt]>=x) {
				tt--;
			}
			if(tt==0) {
			    cout <<"-1"<<" ";
			    stk[++tt]=x;
			}
			else {
				cout <<stk[tt]<<" ";
				stk[++tt]=x;
			}
		}
	}
}

5.

 

#include <iostream>
#include <algorithm>
using namespace std;
const int N=14;
int a[N];//cun zui hou mei wei de shu zi
bool book[N];//biao ji yong guo de shu zi
int ans;
void dfs(int u){
	if(u==10){
		if(a[1]*100+a[2]*10+a[3]+a[4]*100+a[5]*10+a[6]==a[7]*100+a[8]*10+a[9]) ans++;
		return;
	}
	else {
		for(int i=1;i<=9;i++){
			if(!book[i]){
				a[u]=i;
				book[i]=true;
				dfs(u+1);
				book[i]=false;
			}
		}
	}
}
int main(){
	dfs(1);
	cout <<ans/2<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值