- 由0到4五个数字,组成5位数,每个数字用一次,但十位和百位不能为3(当然万位不能为0),输出所有可能的五位数`
#include<iostream>
using namespace std;
int main()
{
for(int a=1;a<=4;a++)
{
int sum=0;
for(int b=0;b<=4;b++)
{
if(a==b)
continue;
for(int c=0;c<=4;c++)
{
if(c==3)
{
c++;
}
if(a==c||c==b)
continue;
for(int d=0;d<=4;d++)
{
if(d==3)
{
d++;
}
if(a==d||b==d||c==d)
continue;
for(int e=0;e<=4;e++)
{
sum=a*10000+b*1000+c*100+d*10+e;
cout<<sum<<" ";
}}}}}}}
2.最大子段和问题。给定由n个整数组成的序列,求序列中子段的最大和,若所有整数均为负整数时定义最大子段和为0。
例如, 当(a1,a2,a3,a4 ,a5,a6) = (-2,11,-4,13,-5,-2)时,最大子段和为: a2+a3+a4=20
输入格式:第一行输入整数个数n(1≤n≤10000),再依次输入n个整数。
输出格式:输出第一行为最大子段和,第二行为子段第一个数和最后一个数在整个序列中的位序。
输入样例1: 5 -2 11 -4 13 -5 -2
输出样例1: 20 2 4
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v;
int n,k;
int s=0,e=0,count=0,sum=0;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>k;
v.push_back(k);
}
for(int j=0;j<v.size();j++)
{
if(count>0)
count=count+v[j];
else
{
count=v[j];
s=j;
}
if(count>sum)
{
sum=count;
e=j;
}
}
cout<<sum<<" "<<s+1<<" "<<e+1<<endl;
return 0;
}
3.有两队选手每队5人进行一对一的比赛,甲队为A、B、C、D、E,乙队为J、K、L、M、N,经过抽签决定比赛对手名单。规定A不和J比赛, M不和D及E比赛。列出所有可能的比赛名单。
#include<iostream>
using namespace std;
int main()
{
char st1[5]={'A','B','C','D','E'},st2[5]={'J','K','L','M','N'};
int i=0,j,k,l,m,n;
for(j=0;j<5;j++)
{
if(j==0)
continue;
for(k=0;k<5;k++)
{
if(k==j)
continue;
for(l=0;l<5;l++)
{
if(l==j||l==k)
continue;
for(m=0;m<5;m++)
{
if(m==j||m==k||m==l)
continue;
if(m==3)
continue;
for(n=0;n<5;n++)
{
if(n==3)
continue;
if(n==j||n==k||n==l||n==m)
continue;
cout<<st1[0]<<"-"<<st2[j]<<" "<<st1[1]<<"-"<<st2[k]<<" ";
cout<<st1[2]<<"-"<<st2[l]<<" "<<st1[3]<<"-"<<st2[m]<<" ";
cout<<st1[4]<<"-"<<st2[n]<<endl;
i++;
}
}
}
}
}
return 0;
}
教材58页习题算法设计题第(1)小题。
#include <iostream>
using namespace std;
int main()
{
int x;
int flag;
int i,j;
for(i=1000;i<2000;i++)
{
flag=1;
x=i;
for(j=1;j<=5;j++)
{
if(x%4!=0)
flag=0;
x=(x+x/4)-1;
}
if(flag&&(x+1)%5==0)
cout<<x<<endl;
}
return 0;
}
教材59页习题算法设计题第(2)小题。
#include<iostream>
using namespace std;
int main()
{
int max=0;
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
int b=i;
while(b!=1)
{
if(b%2==0)
b/=2;
else
b=b*3+1;
if(max<b)
max=b;
}
}
cout<<max<<endl;
return 0;
}