poj 2481 Cows——树状数组&&python
题意:有$n$头牛,每只牛都有一个范围值$[S, E]$,如果对于牛i和牛j来说,它们的测验值满足下面的条件则证明牛i比牛j强壮:$S_i \leq S_j \ and \ E_j \leq E_i \ and \ E_i-S_i > E_j-S_j$。请输出每头牛有几头牛比其强壮。
分析:
我们可以对$S$按从小到大排序,$E$按从大到小排序
如果当前所求的$i$的$s[i]==s[i-1] \ and \ e[i]==e[i-1]$,那么$ans[i]=ans[i-1]$,
否则便是查询排序后在他前面的牛的$e$大于等于他的数目(可以利用树状数组去维护)
#include<algorithm> #include<cstdio> #include<cstring> using namespace std; const int maxn = 100000 + 10; struct Node{ int s, e, id; }cows[maxn]; int C[maxn], num, ans[maxn], n; bool cmp(Node a, Node b) { if(a.s == b.s) return a.e > b.e; else return a.s < b.s; } int lowbit(int x) { return x & -x; } int sum(int x) { int ret = 0; while (x > 0) { ret += C[x]; x -= lowbit(x); } return ret; } void add(int x, int d) { while (x <= num) { C[x] += d; x += lowbit(x); } } int main() { while(scanf("%d", &n) == 1 && n) { num = 0; for(int i = 0;i < n;i++) { scanf("%d%d", &cows[i].s, &cows[i].e); cows[i].id = i; num = max(num, cows[i].e); } sort(cows, cows+n, cmp); memset(C,0,sizeof(C)); for(int i = 0;i < n;i++) { if(i == 0) ans[cows[i].id] = 0; if(cows[i].s == cows[i-1].s && cows[i].e == cows[i-1].e) ans[cows[i].id] = ans[cows[i-1].id]; else ans[cows[i].id] = i - sum(cows[i].e-1); add(cows[i].e, 1); } for(int i = 0;i < n;i++) printf("%d%c", ans[i], i == n-1 ? '\n' : ' '); } return 0; } /* 3 1 1 1 2 2 3 */
python,结构体排序用list模拟
import functools maxn = 100000 + 10; C = [0]*maxn num = 0 ans = [0]*maxn n = 0 def cmp(a, b): if a[0] == b[0]: if a[1] > b[1]: return -1 elif a[1] < b[1]: return 1 else: return 0 else: if a[0] < b[0]: return -1 else: return 1 def lowbit(x): return x & -x def sum(x): ret = 0 while x > 0: ret += C[x] x -= lowbit(x) return ret def add(x, d): while x <= num: C[x] += d x += lowbit(x) while(True): n = int(input().strip()) if n == 0: break num = 0 cows = [[0 for col in range(3)] for row in range(n)] for i in range(n): cows[i][0], cows[i][1] = map(int, input().strip().split()) cows[i][2] = i num = max(num, cows[i][1]) cows = sorted(cows, key=functools.cmp_to_key(cmp)) #print(cows) for i in range(0, num+1): C[i] = 0 for i in range(n): if i == 0: ans[cows[i][2]] = 0 if cows[i][0] == cows[i-1][0] and cows[i][1] == cows[i-1][1]: ans[cows[i][2]] = ans[cows[i-1][2]] else: ans[cows[i][2]] = i - sum(cows[i][1]-1) add(cows[i][1], 1) for i in range(n): print(ans[i])
个性签名:时间会解决一切