sicily 1050 Numbers & Letters
2011-12-30 18:22
399 查看
//使用回溯法遍历进行深度搜索,需要注意两点:一个是除数为0及两个数大小问题,另外一个是减法,跟位置有关系。
#include <iostream> #include <stdlib.h> using namespace std; #define N 5 long array ; long target; long result; bool flag; long add_my(long a,long b) { return a+b; } long sub_my(long a,long b) { return a-b; } long mul_my(long a,long b) { return a*b; } long div_my(long a,long b) { if(a<b) { long temp=a; a=b; b=temp; } if(b==0||a%b!=0) { return -1; } return a/b; } void dfs(long arr[], int size); int main() { int n; cin>>n; for(int i=0;i<n;i++) { result=-2000000000; for(int j=0;j<N;j++) { cin>>array[j]; } cin>>target; for(int j=0;j<N;j++) { if(array[j]<=target&&array[j]>result) { result=array[j]; } } flag=false; //开始回溯 dfs(array,N); cout<<result<<endl; } system("pause"); return 0; } void dfs(long arr[], int size) { if(flag) { return ; } if(arr[0]<=target&&arr[0]>result) { result=arr[0]; if(result==target) { flag=true; return; } } if(size==1) { return ; } long temp[5]; for(int i=0;i<size;i++) { for(int j=i+1;j<size;j++) { for(int k=0,l=1;k<size;k++) { if(k!=i&&k!=j) { temp[l]=arr[k]; l++; } } temp[0]=add_my(arr[i],arr[j]); dfs(temp,size-1); temp[0]=sub_my(arr[i],arr[j]); dfs(temp,size-1); temp[0]=-sub_my(arr[i],arr[j]); dfs(temp,size-1); temp[0]=mul_my(arr[i],arr[j]); dfs(temp,size-1); temp[0]=div_my(arr[i],arr[j]); if(temp[0]!=-1) { dfs(temp,size-1); } } } }
相关文章推荐
- [sicily online]1050. Numbers & Letters
- Sicily 1050 Numbers & Letters
- Sicily 1050 Numbers & Letters(DFS)
- sicily 1050. Numbers & Letters
- sicily1050 Numbers & Letters
- Sicily 1050. Numbers & Letters
- Sicily 1050. Numbers & Letters
- Sicily 1050. Numbers & Letters
- Sicily 1050. Numbers & Letters
- Sicily 1050. Numbers & Letters
- sicily 1050 Numbers & Letters
- sicily 1050 Numbers & Letters
- sicily1050-Numbers & Letters
- sicily 1050. Numbers & Letters
- sicily 1050.Numbers & Letters
- 1050. Numbers & Letters
- sicily 1050 Numbers & Letters
- Sicily 1796. Max's kingdom
- POJ 1504 Adding Reversed Numbers…
- HDU 1058 Humble Numbers && NOJ 1420 丑数 (数位dp)