[Greedy] water line connection

[Greedy] water line connection

topic

Title Description

N-line in front of a personal contact tap water, ground water if each time T_i, please find this programming individual queue n in a sequential, such that n individual minimum average waiting time.

Input Format

Conduct a first integer n.

The second line n integers, the first integer i denotes the i T_i individual waiting time T i.

Output Format

Output file has two lines, a first order behavior having an average shortest time queue; (accurate output result after two decimal places) the average waiting time in the second embodiment are arranged such behavior.

Sample input and output

Input # 1 replication
10
56 is 12 is 1,991,000,234,335,599,812
output # 1 replication
32781496105
291.90

Instructions / tips,

n≤1000, ti ≤10 ^ 6, ti does not guarantee non-repetition. When ti is repeated according to input order (sort it is possible)

analysis

The need to preserve the original number, then open the data stored in the structure. Press the waiting time from small to large

(Here bit read latency, the time is too readily appreciated as the person needs to wait.)
Entitled meaning
First, the first person water, then the second to n people have to wait a [1] seconds, so The total waiting time is a [1] * (n- 1).
Similarly, the second person then water, in the third to n individual he will have to wait behind a [2] s, the total time plus a [2] * (n- 2).
For each individual, the presence of residual everyone must experience a kick of his time.

That is, each person not wait for his own time, who came in behind him and so everyone needs to wait his time. (No wonder the beginning how to play how wrong ...)

Code

#include<iostream>
#include<cstdio>
using namespace std;

#include<algorithm>


int n;
//int t[1005];
struct data{
	int t;
	int num;
}d[1005];

bool cmp(data a,data b){
	return a.t < b.t;
}
int main(){
	int n;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>d[i].t;
		d[i].num =i;
	}
	
	sort(d+1,d+n+1,cmp);
	double cnt1=0,cnt2=0;
	for(int i=1;i<=n;i++){
		cout<<d[i].num<<" ";
		cnt1 += d[i].t;
		cnt2 += cnt1 -d[i].t;
	//	cnt1 +=d[i].t * (n-i);				//也可以把上两句 注释掉,用 公式来。
	}

	printf("\n");
	printf("%.2f",cnt2/n);
	
	
	return 0;
}
Published 75 original articles · won praise 1 · views 3661

Guess you like

Origin blog.csdn.net/A793488316/article/details/104548086