------------恢复内容开始------------
7-9 小字辈 (25分)
题目链接:https://pintia.cn/problem-sets/1316714145967362048/problems/1316715025278029824
思路:就是深度优先搜索,访问的时候标记一下。做到O(n)的时间复杂度。
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; typedef long long ll; const int N = 100010; bool cmp(int a, int b){ return a > b; } int parent[N], len[N]; int fun(int i){ if(parent[i] == -1){ len[i] = 1; return 1; } if(len[parent[i]] >= 1){ len[i] = len[parent[i]] + 1; return len[i]; } len[i] = fun(parent[i]) + 1; return len[i]; } int main() { int n; scanf("%d", &n); int res = 0; for(int i = 1;i <= n; ++ i){ parent[i] = i; } for(int i = 1;i <= n; ++ i){ int x; scanf("%d", &x); parent[i] = x; } for(int i = 1;i <= n; ++ i){ fun(i); res = max(len[i], res); } printf("%d ", res); int cnt = 0; for(int i = 1; i <= n; ++ i){ if(res == len[i] && !cnt) printf("%d", i), cnt ++; else if(res == len[i] && cnt) printf(" %d", i) , cnt ++; } }
Power Sequence
原题链接:https://codeforces.com/problemset/problem/1397/B
思路:暴力求解...
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 100010; ll Pow(ll a, ll b){ ll res = 1; for(int i = 1;i <= b; ++ i){ res *= a; } return res; } bool cmp(int a, int b){ return a > b; } int a[N]; ll ans; int main() { // cout << Pow(2, 5); int n; scanf("%d", &n); for(int i = 1;i <= n; ++ i){ scanf("%d", &a[i]); ans += abs(a[i] - 1); } if(n > 62){ printf("%lld ", ans); return 0; } sort(a + 1,a + 1 + n); ll res = ans; for(ll i = 1;i <= 1e6;i ++){ if(Pow(i, n - 1) > 1e15 || Pow(i, n - 1) < 0) break; ans = abs(a[1] - 1); for(ll j = 2;j <= n; ++ j){ ll tmp = Pow(i, j - 1); ans += abs(a[j] - tmp); } res = min(ans, res); } printf("%lld ",res); }
------------恢复内容结束------------