B. Lucky Number 2
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits4 and7. For example, numbers47,744,4 are lucky and5, 17,467 are not.
Petya loves long lucky numbers very much. He is interested in theminimum lucky numberd that meets some condition. Let cnt(x) be the number of occurrences of numberx in numberd as a substring. For example, ifd = 747747, thencnt(4) = 2,cnt(7) = 4,cnt(47) = 2,cnt(74) = 2. Petya wants the following condition to fulfil simultaneously:cnt(4) = a1,cnt(7) = a2,cnt(47) = a3,cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integersa1,a2, a3 anda4 (1 ≤ a1, a2, a3, a4 ≤ 106).
Output
On the single line print without leading zeroes the answer to the problem — the minimum lucky numberd such, thatcnt(4) = a1,cnt(7) = a2,cnt(47) = a3,cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
2 2 1 1
4774
4 7 3 1
-1
假设4 7 47 74 的个数分别为abcd
分情况讨论:
当c >= d时
构造序列474747...47(c个47),此序列中包含c-1个74
当d < c-1时,无论在这个序列中怎么添加4或7都不能减少74的个数,因此此时无解
当d = c-1时,这个序列恰好满足3,4条件,所以只要将剩下的所有4放在这个序列的左部,剩下的7放在右部就是最终序列
当d = c 时,因为构造的序列已经包含了c-1个74,因此只需要再构造一个74,在剩下的4里拿出一个放在最终序列的末尾就行.
当d > c时
构造序列747474...74(d个74),此序列中包含d-1个47
当c < d-1 时,无论在构造的序列中怎么添加4或7都不能减少47个个数,此时无解
当c = d-1 是,构造序列已经满足了3,4条件,但此时不能简单的将剩下的4加在构造序列的前部,也不能将剩下的7加在构造序列的尾部,因为如果这样会使序列不再满足3,4条件,
当d > 1时最终序列应该是这样的7(剩下的4)47474....7(剩下的7)4 ,当d = 1时序列应该是这样(剩下的7)74(剩下的4)
上面是解决问题的思路,这题还有一个闹心的地方是对无解的判断比较麻烦,在这上错了3次
代码在Wa之后一点一点完善的,逻辑有些冗余
#include<iostream> using namespace std; int main() { int i ,a ,b ,c ,d ; while(cin>>a>>b>>c>>d && a|b|c|d) { if(a-c <0 || b -c<0 || a - d <0 || b - d < 0) { cout<<"-1"<<endl; continue; } if(c >= d) { if(d < c-1) { cout<<"-1"; } else if( d == c-1) { if(a-c>=0 && b-c>=0) { for(i = 0 ; i < a - c ;i ++) cout<<'4'; for(i = 0 ; i < c ;i ++) cout<<"47"; for(i = 0 ; i < b - c ; i++) cout<<'7'; } else cout<<'-1'; } else if( c==d && c!=0 ) { if(a-c>0 && b-c>=0) { for(i = 0 ; i < a - c - 1 ;i ++) cout<<'4'; for(i = 0 ; i < c ;i ++) cout<<"47"; for(i = 0 ; i < b - c ; i++) cout<<'7'; cout<<'4'; } else if(a-c==0 && b-c>0) { cout<<'7'; for(i = 0 ; i < a - c ;i ++) cout<<'4'; for(i = 0 ; i < c ;i ++) cout<<"47"; for(i = 0 ; i < b - c -1;i++) cout<<'7'; } else cout<<"-1"; } else cout<<"-1"; } else { if(c < d-1) { cout<<"-1"; } else { if(d>1 && a-d>=0 && b-d>=0) { cout<<'7'; for(i = 0 ; i < a - d ;i ++) cout<<'4'; cout<<'4'; for(i = 0 ; i < d -2 ;i ++) cout<<"74"; if(d >1) cout<<'7'; for(i = 0 ; i < b - d ; i++) cout<<'7'; if(d>1) cout<<'4'; } else if(a - d >=0 && b - d>=0) { for(i = 0 ; i < b ; i++) cout<<'7'; for(i = 0 ; i < a - d ;i ++) cout<<'4'; cout<<'4'; } else cout<<"-1"; } } cout<<endl; } return 0; }