1. 程式人生 > >hihocoder-編程練習賽-34

hihocoder-編程練習賽-34

turn 當前 scanf 關註 獲取 題目 log tle ble

hihocoder-編程練習賽-34

題目1:

“共同富裕”

時間限制:10000ms 單點時限:1000ms 內存限制:256MB

描述

給定一個數組A1, A2, ... AN,每次操作可以從中選定一個元素Ai,把除了Ai之外的所有元素都加1。

問最少幾次操作可以實現“共同富裕”,即數組中所有元素都相等。

例如對於[1, 1, 1, 2, 3]經過3步:[1, 1, 1, 2, 3] -> [2, 2, 2, 3, 3] -> [3, 3, 3, 3, 4] -> [4, 4, 4, 4, 4]。

輸入

第一行包含一個整數N。(1 ≤ N ≤ 100000)
以下N行包含N個整數A1, A2, ... AN。 (1 ≤ Ai ≤ 100000)

輸出

最小的操作數

樣例輸入
5  
1  
1  
1  
2  
3
樣例輸出
3

使用貪心算法, 對數組進行sort之後,按照每一個元素與最小元素的累計差,就是ans。

#include <cstdio> 
#include <cstdlib> 

const int MAXN = 100000 + 10; 

int num[MAXN]; 

int cmp(const void *a, const void *b){
	return (*(int *)a - *(int *)b); 
}

int main(){ 
	
	int n; 
	while(scanf("%d", &n) != EOF){ 
		for(int i=0; i<n; ++i){
			scanf("%d", &num[i]);  
		}
		qsort(num, n, sizeof(num[0]), cmp); 
		long long ans = 0; 
		for(int i=n-1; i>0; --i){
			ans += num[i] - num[0]; 
		}
		printf("%lld\n", ans ); 
	} 
	return 0; 
}

  

題目2 : 股票價格3

時間限制:10000ms 單點時限:1000ms 內存限制:256MB

描述

小Hi最近在關註股票,為了計算股票可能的盈利,他獲取了一只股票最近N天的價格A1~AN。

小Hi想知道,對於第i天的股票價格Ai,幾天之後股價會第一次超過Ai。

假設A=[69, 73, 68, 81, 82],則對於A1=69,1天之後的股票價格就超過了A1;對於A2=73,則是2天之後股票價格才超過A2。

輸入

第一行包含一個整數N。

以下N行每行包含一個整數Ai。

對於50%的數據,1 ≤ N ≤ 1000

對於100%的數據,1 ≤ N ≤ 100000, 1 ≤ Ai ≤ 1000000

輸出

輸出N行,其中第i行代表對於第i天的股票價格Ai,幾天之後股價會第一次超過Ai。

如果Ai+1~AN之內沒有超過Ai,輸出-1。

樣例輸入
5  
69  
73  
68  
81  
82
樣例輸出
1  
2  
1  
1  
-1

同樣是貪心的思想,

從後面開始向前掃,用stack來保存當前的最近最大num就行了。

#include <cstdio> 
#include <cstdlib> 

const int MAXN = 100000 + 10; 

int num[MAXN], stack[MAXN], ans[MAXN], stack_id[MAXN];  

int main(){ 
	
	int n, top; 
	while(scanf("%d", &n) != EOF){
		for(int i=0; i<n; ++i){
			scanf("%d", &num[i]); 
		}
		top = 0; 
		stack[ top ] = num[n-1]; 
		stack_id[ top++ ] = n-1; 
		ans[ n-1 ] = -1; 

		for(int i=n-2; i>=0; --i){
			if( num[i] < stack[top-1] ){
				ans[ i ] = stack_id[ top-1 ] - i;  
			}else{
				while(top>0 && num[i] >= stack[top-1]){
					--top; 
				}
				if(top == 0){
					ans[ i ] = -1; 
				}else{
					ans[ i ] = stack_id[ top-1 ] - i; 
				}
			}
			stack[ top ] = num[i]; 
			stack_id[ top++ ] = i; 
		}

		for(int i=0; i<n; ++i){
			printf("%d\n", ans[i] );
		}
	}
	return 0; 
}

  

hihocoder-編程練習賽-34