A.Sasha and Array Coloring
思路:贪心
#include<bits/stdc++.h>
using namespace std ;
const int maxn = 1e2 + 10 ;
int a[maxn] ;
void deal (){
int n ; cin >> n ;
for(int i = 0 ; i < n ; i++) cin >> a[i] ;
sort(a , a+n) ;
int sum = 0 ;
for(int i = 0 , j = n-1 ; i < j ; i++ , j--){
sum += a[j] - a[i] ;
}
cout << sum << endl ;
}
int main (){
int t = 1 ; cin >> t ;
while(t--){
deal() ;
}
}
B. Long Long
思路:不要读入0,operation次数就是连续负数段的个数
#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
void deal (){
int n ; cin >> n ;
vector<int > v ;
ll sum = 0 , ans = 0 ;
for(int i = 0 ; i < n ; i++){
int x ;
cin >> x ;
if(x == 0) continue ;
if(x > 0 && v.size() > 0 && v[v.size()-1] < 0) ans ++ ;
v.push_back(x) ;
sum += abs(x) ;
}
if(v.size() > 0 && v[v.size()-1] < 0) ans ++ ;
cout << sum << " " << ans << endl ;
}
int main (){
int t = 1 ; cin >> t ;
while(t--){
deal() ;
}
}
C. Sum in Binary Tree
思路:从n到1逆着推,累加
#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
void deal (){
ll n ; cin >> n ;
ll sum = 0 ;
while(n != 1){
sum += n ;
n /= 2 ;
}
cout << sum+1 << endl ;
}
int main (){
int t = 1 ; cin >> t ;
while(t--){
deal() ;
}
}
思路:题意是求x结点下的叶子节点个数乘上y结点下的叶子节点个数。观察数据大小时间复杂度只能是O(t*(n+q)),则要求这棵树下每一个结点下叶子结点有几个,因为题目只给了俩个点是父子,没说谁是父,谁是子,所以要用根节点是1来求整个树的结构。
#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
const int maxn = 2e5 + 10 ;
vector<ll > t ;
vector<vector <int > > child ;
int dfs(int root){
if(child[root].size() == 0){//若是叶子节点
t[root] = 1 ;
}else{
for(int i = 0 ; i < child[root].size() ; i++){
t[root] += dfs(child[root][i]) ;
}
}
return t[root] ;
}
void deal (){
int n ;
scanf("%d" , &n) ;
vector<int > vis(n+1 , 0) ;
vector<vector <int > > edge(n+1) ;
child.assign(n+1, vector<int>());
for(int i = 0 ; i < n-1 ; i++){
int u , v ;
scanf("%d%d" , &u , &v) ;
edge[u].push_back(v) ;
edge[v].push_back(u) ;
//child[u].push_back(v) ;
}
//用类似bfs的方法求树的结构
queue<int > q ;
q.push(1) ;
while(!q.empty()){
int t = q.front() ;
q.pop() ;
vis[t] = 1 ;
for(int i = 0 ; i < edge[t].size() ; i++){
if(!vis[edge[t][i]]){
child[t].push_back(edge[t][i]) ;
q.push(edge[t][i]) ;
}
}
}
t.assign(n+1, 0);
//利用dfs递归求每个结点下的叶子节点
dfs(1) ;
int m ; scanf("%d" , &m) ;
for(int i = 1 ; i <= m ; i++){
int a , b ; scanf("%d%d" , &a , &b) ;
long long ans = t[a] * t[b] ;
printf("%lld\n" , ans) ;
}
}
int main (){
int t = 1 ; cin >> t ;
while(t--){
deal() ;
}
}