蛮力法例题

1.大整数问题

在这里插入图片描述

#include <iostream>
using namespace std;

int main()
{
	int n;
	int sum=0;
	cin >> n;
	
	while(n>0){
		sum += n%100;
		n=n/100;
	}
	
	if(sum%11==0)
		cout << "该整数能被11整除";
	else
		cout << "该整数不能被11整除"; 
}

2.模式匹配问题

在这里插入图片描述

#include <iostream>
#include <cstring>
using namespace std;

int main()
{	
	char s[1000] = {'s'}; //主串 
	char t[100] = {'t'}; //模式串 
	int next[100] = {0};
	
	//输入主串和模式串 
	cin >> s+1;
	cin >> t+1;
	
	int s_len = strlen(s)-1; //主串长度 
	int t_len = strlen(t)-1; //模式串长度 
	int i,j,k;  
	
	//求模式串的next数组 
	j = 1;k = 0;
	next[j]=0;
	while(j < t_len) { 
		if(k == 0 || t[j] == t[k]) {
			j++;
			k++;
			next[j] = k; // next[j+1]=next[j]+1
		}
		else 
			k = next[k];
	}
	
	// 输出next数组 
	for(i=1; i<=t_len; i++)
		cout <<"next["<<i<<"]="<< next[i] <<endl;

	//KMP  
	i=0;j=0;
	while(i<s_len && j<t_len) { //均未到达串尾
		//cout << i <<","<< j<<endl;
		if(j==0 || s[i] == t[j]) {
			i++;
			j++;
		}
		else
			j = next[j];
	}
	
	if(j>=t_len)
		cout << "模式在文本中的位置是"<<i-1<<endl;
	else 
		cout << "匹配失败"<<endl;
}

3.线性规划问题

在这里插入图片描述

#include<iostream>
using namespace std;

int main()
{
	int x,y,i,j,max=0;
	for(i=0; i<=4; i++) {
		for(j=0; j<=2; j++) {
			if(max < 3*i+5*j) {
				if(i+j <= 4 && i+3*j <= 6) {
					max = 3*i+5*j;
					x = i;
					y = j;
				}
			}
		}
	}
	cout << x << endl;
	cout << y << endl;
	cout << max << endl;
}

4.变位词问题

在这里插入图片描述

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	char s[100];
	char t[100];
	
	gets(s);
	gets(t);
	
	int i; 
	int s_count[26] = {0};
	int t_count[26] = {0};
 
 	// 统计s各个字符频率 
	for(i=0; i<strlen(s);i++) {
		if(s[i] > 32)
			s_count[s[i]-97]++;
	}
	
 	// 统计t各个字符频率	
	for(i=0; i<strlen(t);i++){
		if(t[i] > 32)
			t_count[t[i]-97]++;
	}
	
	// 比较s和t中各个字符频数是否相等 
	for(i=0; i<26; i++)
		if(s_count[i] != t_count[i]) break;
	
	
	if(i>=26) cout << "是变位词" << endl; 
	else cout << "不是变位词" << endl;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值