1103 Integer Factorization (30 points)【DFS+Pruning】

Poke here

main idea:

For three positive integers N, K, and P, express N as the sum of P powers of K positive integers (which can be the same, in descending order). If there are multiple schemes, choose the scheme with the largest base n1+…+nk. There are many schemes, choose the scheme with the largest lexicographic order of the base sequence.

Idea: Liu Wei

Code:

#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int n,k,p,maxFacSum=-1;
vector<int> v,ans,tempans;
void dfs(int index,int tempk,int tempSum,int factSum){
	if(tempk==k){
		if(tempSum==n&&factSum>maxFacSum){
			maxFacSum=factSum;
			ans=tempans;	//**这个真的可以! 
		}
		return ;
	}
	while(index>=1){
		if(tempSum+v[index]<=n){
			tempans[tempk]=index;
			dfs(index,tempk+1,tempSum+v[index],factSum+index);
			//这里index不减1,因为可以有多个相同的数的p次方相加 
		}
		if(index==1) return ;
		index--;
	}
}

int main(){
	cin>>n>>k>>p;
	tempans.resize(k);
	int i=0;
	while(pow(i,p)<=n){
		v.push_back(pow(i,p));
		i++;
	}
	dfs(v.size()-1,0,0,0);
	if(maxFacSum==-1) {
		cout<<"Impossible";
		return 0; 
	}
	printf("%d = ",n);
	for(int i=0;i<ans.size();i++){
		if(i>0) printf(" + ");
		printf("%d^%d",ans[i],p);
	}
	return 0;
} 

 Introduction:  a vector is assigned to another vector

  1. vector<int> v1(v2);//声明

     

  2. vector<int> v1;//声明v1
    v1.assign(v2.begin(), v2.end());//将v2赋值给v1
    
  3. #include<iostream>
    #include<vector>
    using namespace std;
    vector<int> v1();
    v1.swap(v2);//将v2赋值给v1
  4. vector<int>::iterator it;//声明迭代器
    for(it = v2.begin();it!=v2.end();++it)//遍历v2,赋值给v1
    {
         v1.push_back(*it);
    }
  5. (The most recommended one)
    #include<iostream>
    #include<vector>
    using namespace std;
    int main(){
    	vector<int> v1,v2;
    	for(int i=1;i<10;i++){
    		v1.push_back(i);
    	}
    	v2=v1;
    	cout<<"v2数组的值:"<<endl; 
    	for(int i=0;i<v2.size();i++)
    		cout<<v2[i]<<" ";
    		return 0;
    }

    Result: It's really not a bit more convenient, the last one! ! !

Guess you like

Origin blog.csdn.net/WKX_5/article/details/114583092