CF1497E1 Square-free division (easy version)(set写法)
Square-free division (easy version)
This is the easy version of the problem. The only difference is that in this version k=0.
There is an array a1,a2,…,an of n positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.
Moreover, it is allowed to do at most k such operations before the division: choose a number in the array and change its value to any positive integer. But in this version k=0, so it is not important.
What is the minimum number of continuous segments you should use if you will make changes optimally?
Input
The first line contains a single integer t (1≤t≤1000) — the number of test cases.
The first line of each test case contains two integers n, k (1≤n≤2⋅105, k=0).
The second line of each test case contains n integers a1,a2,…,an (1≤ai≤107).
It's guaranteed that the sum of n over all test cases does not exceed 2⋅105.
Output
For each test case print a single integer — the answer to the problem.
解题思路
另一种写法
主要思路: 把每一个数字因子中包涵的完全平方数去除,如果一段内有任意两个数字剩下的因子乘积相同,那么这两个数乘积将会是一个完全平方数,所以段数++。
代码
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int MAXN = 1e7 + 10; 4 int sq[MAXN]; 5 void pre() //预处理范围内每一个数对应的除去完全平方后剩余的因子成绩 6 { 7 for (int i = 1; i < MAXN; i++) 8 sq[i] = i; //一开始为该数字本社 9 for (int i = 2; i * i < MAXN; i++) 10 { 11 for (int j = i * i; j < MAXN; j += i * i) 12 while (sq[j] % (i * i) == 0) //去除完全平方因子 13 sq[j] /= i * i; 14 } 15 } 16 int a[MAXN]; 17 void solve() 18 { 19 int n, k; 20 cin >> n >> k; 21 set<int> st; 22 int ans = 0; 23 for (int i = 0; i < n; i++) 24 cin >> a[i]; 25 for (int i = 0; i < n; i++) 26 { 27 a[i] = sq[a[i]]; //转换 28 if (st.count(a[i])) //如果有相同的出现过,那么增加新的一段 29 { 30 ans++; 31 st.clear(); 32 } 33 st.insert(a[i]); 34 } 35 cout << ans + 1<<"\n"; //最后一段没有统计,所以结果+1 36 } 37 int main() 38 { 39 ios::sync_with_stdio(false); 40 cin.tie(0); 41 pre(); 42 int t; 43 cin >> t; 44 while (t--) 45 { 46 solve(); 47 } 48 return 0; 49 }