題目
將 1, 2,..., 9 共 9 個數分成三組,分別組成三個三位數,且使這三個三位數的比例是 A:B:C,試求出所有滿足條件的三個三位數,若無解,輸出 No!!!
。
輸入格式
三個數,A,B,CA,B,C。
輸出格式
若干行,每行 33 個數字。按照每行第一個數字升序排列。
解析
想用next_permutation這個函數,但是實在想不起來用法,於是暴力循環了第一個代碼。
法1不僅需要mark【】數組來標記這個數組是否已經永過,還需要考慮三位數的個位、十位、百位也不相同。
其中十位的數字建議使用
l[1]=i/100;
l[2]=i/10%10;
l[3]=i%10;
暴力循環 i, j , q 這三個三位數。
法二:簡潔許多。昨天的沒保存就關機了。。。
代碼
法1:
int A, B , C;
int mark[10];
int main() {
cin >> A >> B >> C;
int flag = 0;
for(int i = 123 ; i <= 987 ; i ++)
{
memset(mark , 0 , sizeof(mark)); mark[0] = 1;
int bai = i / 100;
// int shi = (i - bai * 100 ) / 10;
int shi = i / 10 % 10;
int ge = i % 10;
//cout << bai <<" " << shi << " " << ge << endl;
if(mark[bai] | mark[shi] | mark[ge]) continue;
if(bai == shi || shi == ge || bai == ge) continue;
mark[bai] = mark[shi] = mark[ge] = 1;
// if ( i == 156 )
// cout << i << " " << mark[1] <<" ";
for(int j = i + 1 ; j <= 987 ; j ++ )
{
int baij = j / 100;
int shij = (j - baij * 100 ) / 10;
int gej = j % 10;
if(baij == shij || shij == gej || baij == gej) continue;
if(mark[baij] | mark[shij] | mark[gej]) continue;
if(i * B != j * A ) continue;
if( j < i) continue;
// if( i == 156 ) cout << j <<" " << shij << endl;
mark[baij] = mark[shij] = mark[gej] = 1;
for(int q = j + 1 ; q <= 987 ; q ++)
{
int baiq = q / 100;
int shiq = (q - baiq * 100 ) / 10;
int geq = q % 10;
if(baiq == shiq || shiq == geq || baiq == geq) continue;
if(mark[baiq] | mark[shiq] | mark[geq]) continue;
// mark[baiq] = mark[shiq] = mark[geq] = 1;
if( q * B != j * C) continue;
cout << i <<" " << j << " " << q << endl;
flag = 1;
}
}
}
if(! flag) cout << "No!!!" << endl;
}
法2:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int A , B , C;
cin >> A >> B >> C;
int num[10] = {0 , 1, 2, 3 , 4 , 5 , 6 , 7 ,8 , 9};
int flag = 0;
do
{
int a = num[1] * 100 + num[2] * 10 + num[3];
int b = num[4] * 100 + num[5] * 10 + num[6];
int c = num[7] * 100 + num[8] * 10 + num[9];
if (a * B == b * A && a * C == c * A)
{
cout << a << " " << b << " " << c << endl;
flag = 1;
}
// cout << a << " " << b << " " << c << endl;
}while(next_permutation(num + 1, num + 10));
if ( !flag) cout << "No!!!" << endl;
}