yukicoder No.118 門松列(2)
問題
N本の竹がありそれぞれの高さはAiで与えられる。
門松列とは、選んだ「3つの竹の長さの降順で2番目が、左または右側になっているもの」、「3つの長さはすべて異なる」という条件も満たすものである。
門松列になるような竹の選び方の数を求めよ。
(竹の並び順が違っても、同じ竹の組み合わせなら同じものとする。それぞれの竹は番号が振ってあるので区別できる。)
感想
N本の竹の中から3つ選ぶ組み合わせは個あり、同じ高さの竹が選ばれると門松列にはならないのでその数だけ引く。
同じ高さの竹がM本ある時
同じ高さの竹から2本選ばれる場合
同じ高さの竹M本の中から2本選び,その他の高さの竹(N-M)本から1本選ぶので、個。
同じ高さの竹から3本選ばれる場合
同じ高さの竹M本の中から3本選ぶので、個。
したがって、ある高さが同じ竹が選ばれる数は個。
それぞれの高さについて門松列にならない数を計算し全体から引いていく。
#include <iostream> #include <string> #include <cmath> #include <vector> #include <cstring> #include <climits> #include <map> #include <queue> #include <algorithm> #include <utility> #define INF INT_MAX / 2 #define MOD 1000000007 using namespace std; typedef pair<int, int> P; typedef long long ll; long long combi3(int n){ return (long long)n*(n-1)*(n-2)/6; } long long combi2(int n){ return (long long)n*(n-1)/2; } long long func(int n,int m){ if(m==2)return n-2; else{ return combi2(m)*(n-m)+combi3(m); } } int main(void) { int n; cin >> n; vector<int> a(n); for(int i=0;i<n;i++){ cin >> a[i]; } map<int,int>counter; for(int i=0;i<n;i++){ counter[a[i]]++; } long long tmp = 0; auto it = counter.begin(); for(;it!=counter.end();it++){ if(it->second > 1){ tmp += func(n,it->second); } } long long ans = combi3(n) - tmp; cout << ans%MOD << endl; }
難しかった。