标签:bre specific ram i++ ace break line dfs include
Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!
Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.
Each input contains one test case. Each case contains one positive integer with no more than 20 digits.
For each test case, first print in a line "Yes" if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or "No" if not. Then in the next line, print the doubled number.
1234567899
Yes
2469135798
思路:
1、求2倍可以认为是两个数相加
2、首先检查加倍后数的位数是否相同,如果不相同则一定不是
3、如果位数相同,我的思路是使用dfs对原数进行深搜,本质是使用了dfs求全排列
4、其他人的思路是判断原数和加倍后的每个数中出现的0-9的个数是否相同(比我的思路好多了,虽然我的也能ac)
#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; vector<int>v1; vector<int>v2; int visited[23]; void doubleNum() { int temp=0;//保存进位 for(auto num:v1) { int a=num*2+temp; if(a>=10) { temp=1; v2.push_back(a-10); } else { temp=0; v2.push_back(a); } } if(temp>0) v2.push_back(temp); reverse(v2.begin(),v2.end()); } void output() { for(auto num:v2) cout<<num; cout<<endl; // cout<<v2[0]<<endl; } bool flag=false; void dfs(int i,int n,int current) { //cout<<v1[i]<<" "<<v2[current]<<endl; if(v1[i]!=v2[current]) return; if(current==n-1) { flag=true; return; } for(int j=0;j<n;j++) { if(visited[j]!=1) { visited[j]=1; dfs(j,n,current+1); visited[j]=0; } } //return false; } int main() { string num; cin>>num; v1.resize(num.size()); for(int i=0;i<num.size();i++) v1[num.size()-1-i]=num[i]-‘0‘; //set<int>s; doubleNum(); if(v1.size()!=v2.size()) { cout<<"No"<<endl; output(); } else { int n=num.size(); int i; for(i=0;i<n;i++) { if(v1[i]==v2[0]) break; } //cout<<i<<endl; visited[i]=1; if(i<n) dfs(i,n,0); if(flag) { cout<<"Yes"<<endl; output(); } else { cout<<"No"<<endl; output(); } } return 0; }
标签:bre specific ram i++ ace break line dfs include
原文地址:https://www.cnblogs.com/zhanghaijie/p/10294757.html