标签:iostream date color time ini ret logs cout copy
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4078 Accepted Submission(s): 1014
1 /* 2 Name: hdu--1104--Remainder 3 Copyright: 版权2017 日天大帝 4 Author: 日天大帝 5 Date: 22/04/17 09:11 6 Description: bfs 7 a = b * q + r (q > 0 and 0 <= r < q), 8 题上的取余运算和%运算不一样,%运算能产生负值所以要 (n%k+k)%k这样,才等于题意的取余 9 这个题用vis标记产生过的数据,同时用%km和%k进行剪枝优化 10 11 */ 12 #include<cstring> 13 #include<iostream> 14 #include<queue> 15 #include<string> 16 using namespace std; 17 struct node{ 18 int num,steps; 19 string str; 20 }; 21 const int MAX = 1005; 22 bool vis[MAX]; 23 int n,m,k,mk,final_cmp; 24 void bfs(){ 25 node start; 26 start.num = n; 27 start.str = ""; 28 start.steps = 0; 29 vis[(n%k+k)%k] = 1; 30 queue<node> q; 31 q.push(start); 32 33 while(!q.empty()){ 34 node a,temp = q.front();q.pop(); 35 if(final_cmp == ((temp.num%k)+k)%k){ 36 cout<<temp.steps<<endl<<temp.str<<endl; 37 return ; 38 } 39 for(int i=0; i<4; ++i){ 40 a = temp; 41 if(i == 0){ 42 a.num += m; 43 a.str += ‘+‘; 44 }else if(i == 1){ 45 a.num -= m; 46 a.str += ‘-‘ ; 47 }else if(i == 2){ 48 a.num *= m; 49 a.str += ‘*‘; 50 }else{ 51 a.num = (a.num%m+m)%m; 52 a.str += ‘%‘ ; 53 } 54 a.num %= mk;//%k之后%m结果就错啦,10%(15) !=10%3%5 55 if(vis[(a.num%k+k)%k])continue;//%k缩小范围剪枝 56 a.steps++; 57 vis[(a.num%k+k)%k] = 1; 58 q.push(a); 59 } 60 } 61 cout<<"0"<<endl; 62 } 63 int main(){ 64 ios::sync_with_stdio(false); 65 66 while(cin>>n>>k>>m,n||m||k){//输入有正负不能用n+m+k 67 memset(vis,0,sizeof(vis)); 68 mk = m*k; 69 final_cmp = ((n+1)%k+k)%k; 70 bfs() ; 71 } 72 return 0; 73 }
标签:iostream date color time ini ret logs cout copy
原文地址:http://www.cnblogs.com/rtdd/p/6747002.html