1、求固定周长P,能构成的直角三角形的个数,要求各边长为整数,P最大为100000,案例要求时间小于1秒
属于数论问题:www.51nod.com上的第1165题,http://www.51nod.com/Challenge/Problem.html#problemId=1165
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
int main(){
int p = 0;
while (cin >> p)
{
clock_t s,e;
s = clock();
int total = 0;
for (int a = 1; a < p/3; a++)
{
double b = p - (double) p * p / (2 * p - 2 * a);
if (a < b && b - (int) b < 1e-5) {
total++;
cout << a<<"\t"<<b<<"\t"<<p-a-b<<endl;
}
}
e = clock();
cout <<e-s<<endl;
cout << total<<endl;
}
return 0;
}
2、寻找是否连通,给定一个数组
{ {1 , 2 ,3 ,4 , 5},
{11,12,13,14,15},
{21,22,23,24,25},
{31,32,33,34,35},
{41,42,43,44,45}};
再给一个6元素的数字序列,判断这个序列是否连通,如1 2 3 4 5 15是连通的,1 2 3 4 5 25就不是(连通就是两个元素之间相邻);
使用广度优先搜索就可以解决
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
bool check(int val,vector<int> v){
if (find(v.begin(),v.end(),val)!=v.end())
{
return true;
}
return false;
}
int main(){
int a,b,c,d,e,f;
int arr[5][5]={
{1,2,3,4,5},
{11,12,13,14,15},
{21,22,23,24,25},
{31,32,33,34,35},
{41,42,43,44,45}};
while(cin >> a >> b >> c >> d >> e >> f){
//使用广度搜索即可
vector<int> v;
v.push_back(a);
v.push_back(b);
v.push_back(c);
v.push_back(d);
v.push_back(e);
v.push_back(f);
//任选一个点进行搜索,将临近的节点放入队列中
vector<int> visited;
queue<int> q;
q.push(a);
while (!q.empty()){
if (check(q.front()+10,v)&&!check(q.front()+10,visited))
{
q.push(q.front()+10);
}
if (check(q.front()-10,v)&&!check(q.front()-10,visited))
{
q.push(q.front()-10);
}
if (check(q.front()+1,v)&&!check(q.front()+1,visited))
{
q.push(q.front()+1);
}
if (check(q.front()-1,v)&&!check(q.front()-1,visited))
{
q.push(q.front()-1);
}
visited.push_back(q.front());
q.pop();
}
if (visited.size()==6)
{
cout << 1 <<endl;
}else{
cout << 0 <<endl;
}
}
system("pause");
return 0;
}
3、典型的DP问题,求解最长公共子序列,给定两个数组A,B,元素的之间互异,A,B之间只是元素顺序不同,求A,B中删除最小个数的元素,使得A=B,如A ={ 1 , 2 , 3 , 4},B={2 , 3 , 1 ,4},最长公共子序列为2 , 3 ,4,所以删除一个就可以了
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
using namespace std;
int main(){
//求解最长公共子序列问题
int n = 0 ;
while(cin >> n){
vector<int> va,vb;
for (int i = 0; i < n; i++)
{
int ele = 0;
cin >> ele;
va.push_back(ele);
}
for (int i = 0; i < n; i++)
{
int ele = 0;
cin >> ele;
vb.push_back(ele);
}
//动态规划求解最长公共子序列
vector<vector<int>> a(n+1,vector<int>(n+1));
for (int i = 0; i <= n; i++){
a[0][i] = 0;
a[i][0] = 0;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (va[i]==vb[j])
{
a[i+1][j+1]=a[i][j]+1;
}else{
a[i+1][j+1]=max(a[i][j+1],a[i+1][j]);
}
}
}
cout << va.size()-a[n][n]<<endl;
}
system("pause");
return 0;
}