题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3932
题面:
Handshakes Time Limit: 2 Seconds Memory Limit: 65536 KBLast week, n students participated in the annual programming contest of Marjar University. Students are labeled from 1 to n. They came to the competition area one by one, one after another in the increasing order of their label. Each of them went in, and before sitting down at his desk, was greeted by his/her friends who were present in the room by shaking hands.
For each student, you are given the number of students who he/she shook hands with when he/she came in the area. For each student, you need to find the maximum number of friends he/she could possibly have. For the sake of simplicity, you just need to print the maximum value of the n numbers described in the previous line.
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains an integer n (1 ≤ n ≤ 100000) -- the number of students. The next line contains n integers a1, a2, ..., an (0 ≤ ai < i), where ai is the number of students who the i-th student shook hands with when he/she came in the area.
For each test case, output an integer denoting the answer.
2 3 0 1 1 5 0 0 1 1 1
2 3Author: LIN, Xi
题意:
已知一序列,每个人在进入房间之后,那一刻与他握手的朋友的个数,求房间内可能拥有朋友数最多的那个人拥有的朋友个数。
解题:
因为给出的序列,只是记录了他进入房间那一刻和他握手的人的人数,之后的并不确定。但我们可以假设之后,凡是有朋友的,都是他的朋友,那么他的朋友数是否为最多的,如果是,则更新最大值。遍历寻找最大值即可。
代码:
#include <iostream> #include <string> #include <cstdio> #include <cstring> #include <map> #include <set> #include <algorithm> #include <cmath> using namespace std; int a[100005],sum[100005]; int main() { int t,n,maxx; scanf("%d",&t); while(t--) { maxx=0; scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&a[i]); } a[n+1]=0; sum[n+1]=0; for(int i=n;i>=1;i--) { if(a[i+1]) { sum[i]=sum[i+1]+1; } else sum[i]=sum[i+1]; if(a[i]+sum[i]>maxx) maxx=a[i]+sum[i]; } printf("%d\n",maxx); } return 0; }