Lightoj 1141 BFS

来源:互联网 发布:淘宝助理5.8 编辑:程序博客网 时间:2024/05/16 15:26

注意是质素因子。。。。。

AC代码如下:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#include <cmath>using namespace std;#define MAX 0x3f3f3f3ftypedef struct{int step;int now;}Node;int s, t;bool prime[1010];int marks[1001];int BFS(){queue<Node> q;Node start;start.now = s;start.step = 0;q.push( start );memset( marks, 0x3f, sizeof( marks ) );int ans = MAX;while( !q.empty() ){Node n = q.front();q.pop();if( n.now == t ){ans = min( ans, n.step );continue;}for( int i = 2; i < n.now; i++ ){if( n.now % i != 0 || !prime[i] ){continue;}if( n.now + i > t ){continue;}if( marks[n.now+i] > n.step + 1 ){Node temp;temp.now = n.now + i;temp.step = n.step + 1;marks[n.now+i] = temp.step;q.push( temp );}}}if( ans < MAX ){return ans;}return -1;}int main(){int T, Case = 1;memset( prime, true, sizeof( prime ) );for( int i = 2; i <= 1000; i++ ){for( int j = 2; i * j <= 1000; j++ ){prime[i*j] = false;}}cin >> T;while( T-- ){cin >> s >> t;cout << "Case " << Case++ << ": " << BFS() << endl;}return 0;}