題目鏈接
http://codeforces.com/gym/101102/problem/C
problem description
Judge Bahosain was bored at ACM AmrahCPC 2016 as the winner of the contest had the first rank from the second hour until the end of the contest.
Bahosain is studying the results of the past contests to improve the problem sets he writes and make sure this won’t happen again.
Bahosain will provide you with the log file of each contest, your task is to find the first moment after which the winner of the contest doesn’t change.
The winner of the contest is the team with the highest points. If there’s more than one team with the same points, then the winner is the team with smallest team ID number.
InputThe first line of input contains a single integer T, the number of test cases.
The first line of each test case contains two space-separated integers N and Q (1 ≤ N, Q ≤ 105), the number of teams and the number of events in the log file. Teams are numbered from 1 to N.
Each of the following Q lines represents an event in the form: X P, which means team number X (1 ≤ X ≤ N) got P( - 100 ≤ P ≤ 100, P ≠ 0) points. Note that P can be negative, in this case it represents an unsuccessful hacking attempt.
Log events are given in the chronological order.
Initially, the score of each team is zero.
OutputFor each test case, if the winner of the contest never changes during the contest, print 0. Otherwise, print the number of the first event after which the winner of the contest didn’t change. Log events are numbered from 1 to Q in the given order.
Example input1output
5 7
4 5
3 4
2 1
1 10
4 8
3 -5
4 2
5
題意:有n個人參加活動,現在有Q次事件,標號從1~Q,每個事件為x p 表示第x個人加上p分(-100=<p<=100&&p!=0) 求到第幾個事件之後冠軍不再變化,冠軍為得分最多的那個人,如果多個人得分相同,冠軍為序號最小的那個人。
思路:先遍歷一遍事件,找到冠軍tmp,然後再從第一個事件開始遍歷,判斷當前的冠軍是否是tmp,如果不是則ans=i+1 第二次遍歷時就是修改a[x[i]]的值,然後判斷最大是是否還是tmp,故可以用RMQ或平衡二叉樹(set集合也是平衡二叉樹,需要自定義排序);
代碼如下:
#include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> #include <set> const int MAXN = 1e5+10; using namespace std; const int INF = 1e9; int a[MAXN], x[MAXN], p[MAXN]; struct compare { bool operator() (const int s1, const int s2) const { if(a[s1]==a[s2]) return s1<s2; return a[s1]>a[s2]; } }; set<int,compare>s; set<int,compare>:: iterator it; int main() { int T; cin>>T; while(T--) { s.clear(); int n, q; memset(a, 0, sizeof(a)); scanf("%d%d",&n,&q); for(int i=1; i<=q; i++) { scanf("%d%d",&x[i],&p[i]); a[x[i]] += p[i]; } int Max = -INF, tmp = -1; for(int i=1; i<=n; i++) { if(a[i] > Max) { Max = a[i]; tmp = i; } } memset(a, 0, sizeof(a)); for(int i=1;i<=n;i++) s.insert(i); //cout<<"++: "<<*s.begin()<<endl; int pos = 0; if(*s.begin()!=tmp) pos=1; for(int i=1; i<=q; i++) { s.erase(x[i]); a[x[i]] += p[i]; s.insert(x[i]); if(*s.begin()!=tmp) pos=i+1; } printf("%d\n",pos); } return 0; }