zoukankan      html  css  js  c++  java
  • 素数+map BestCoder Round #54 (div.2) 1002 The Factor

    题目传送门

    题意:给出一个数列,问数列的乘积的一个满足条件的最小因子是什么,没有输出-1。条件是不是素数

    分析:官方题解:对于每一个数字,它有用的部分其实只有它的所有质因子(包括相等的)。求出所有数的所有质因子中最小的两个,相乘就是答案。如果所有数字的质因子个数不到两个,那么就是无解。时间复杂度O(n*sqrt(a))。用map存质因子,记得开long long

     

    代码:

    /************************************************
    * Author        :Running_Time
    * Created Time  :2015-9-5 19:48:28
    * File Name     :B.cpp
     ************************************************/
    
    #include <cstdio>
    #include <algorithm>
    #include <iostream>
    #include <sstream>
    #include <cstring>
    #include <cmath>
    #include <string>
    #include <vector>
    #include <queue>
    #include <deque>
    #include <stack>
    #include <list>
    #include <map>
    #include <set>
    #include <bitset>
    #include <cstdlib>
    #include <ctime>
    using namespace std;
    
    #define lson l, mid, rt << 1
    #define rson mid + 1, r, rt << 1 | 1
    typedef long long ll;
    const int N = 5e4 + 10;
    const int INF = 0x3f3f3f3f;
    const int MOD = 1e9 + 7;
    int a[110];
    map<int, int> cnt;
    
    void factorize(int n)  {
        for (int i=2; i*i<=n; ++i)    {
            while (n % i == 0)  {
                n /= i;
                cnt[i]++;
            }
        }
        if (n != 1) cnt[n]++;
    }
    
    int main(void)    {
    	int T;	scanf ("%d", &T);
    	while (T--)	{
            cnt.clear ();
    		int n;	scanf ("%d", &n);
    		for (int i=1; i<=n; ++i)	{
    			scanf ("%d", &a[i]);
    		}
    		for (int i=1; i<=n; ++i)	{
    			factorize (a[i]);
    		}
            map<int, int>::iterator it;
            vector<int> ans;
            for (it=cnt.begin (); it!=cnt.end (); ++it) {
                if (it->second)   {
                    for (int i=1; i<=it->second; ++i)    {
                        ans.push_back (it->first);
                        if (ans.size () == 2)   break;
                    }
                }
                if (ans.size () == 2)   break;
            }
            if (ans.size () != 2)   puts ("-1");
            else    {
                printf ("%I64d
    ", ans[0] * 1ll * ans[1]);
            }
    	}
    
        return 0;
    }
    

      

    编译人生,运行世界!
  • 相关阅读:
    KMP算法代码实现记录
    冒泡,插入,希尔,快速,归并,桶排序,堆排序算法汇总实现
    回溯法个人理解记录(C#八皇后)
    C#创建初始化链表的方式(个人目前写出3种创建的方式)
    算法汇总代表性学习记录
    C#集合去重
    C#获取数组/字符串的k个字符的全部组合
    pl/sql简单执行记录个人学习记录
    oracle为什么尽量不要使用外键的最好理解
    PickerController 添加照片---iOS
  • 原文地址:https://www.cnblogs.com/Running-Time/p/4785381.html
Copyright © 2011-2022 走看看