There are N towers in a city. All N towers are placed in a single row.Score of tower i is the the number of towers visible to its right side.
Tower j will be visible to Tower i if it satisfies the following condition,
- If height of tower j is less than the height of tower i, then tower j will be visible to tower i unless it is blocked by some tower whose height is greater than or equal to the height of tower i
- If height of tower j is greater than height of tower i, then Tower j will be visible if it not blocked by any tower whose height is greater than or equal to the height of Tower j
Find the score of each tower.
Input
First line consists of the number T which denotes the number of test cases.
In each test case, the first line contains N, which denotes the number of towers.
Next line contains N integers which denote the height of towers.
Output
For each test case, print N integers which denote the score of each tower.
Constraints
1 <= T <= 100
1 <= N <= 10^5
1 <= height of each tower <= 10^9
Example
Input: 2 9 4 2 3 1 5 2 7 6 9 3 1 2 2 Output: 6 4 4 3 3 2 2 1 0 1 1 0
Explanation
Example case 1.
For tower 1, Towers 2,3,4,5 will be visible (as they are not blocked by any tower whose height is greater than tower 1). Tower 6 will be blocked by 6. Tower 7 will be visible as it is not blocked by any bigger tower in front of it. Tower 8 will be blocked by tower 7. Tower 9 will be visible because it's height is greater than the blocking tower (which is tower 5).
Example Case 2. For tower 1,
Tower 2 will be visible. Tower 3 will be blocked by tower 2.
http://www.codechef.com/KRKS2015/problems/K15C
当时做的时候超时,方法不太好。大神的代码方法很巧妙~
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int main(){
int t;
scanf("%d",&t);
while(t--){
long long int n;
scanf("%lld",&n);
long long int arr[n],b[n];
long long int i,k,j;
for(i=0;i<n;i++){
scanf("%lld",&arr[i]);
b[i]=0;
}
for (i=n-1;i>=0;i--){
for(k=i+1;k<n;k++){
if(arr[k]>arr[i]){
b[i]=1+b[k]; //求后面比它高的塔的个数
break;
}
}
}
for(int i=0;i<n;++i)
cout<<b[i]<<" ";
cout<<endl;
for (i=0;i<n;i++){
long long temp=0;
for (k=i+1;k<n;k++) {
if(arr[k]<=arr[i]) //找后面比它矮的
temp++;
else{
temp+=(b[k]+1);
break;
} //找到比它高的,加上,再break
}
printf("%lld ",temp);
}
}
return 0;
}