UVA11401 Triangle counting 題解

博客園同步

原題鏈接

簡要題意:

若干組數據,每組數據給出一個 nn ,求出 三邊均 n\leq n 且互不相等 的三角形個數。兩個三角形不同當且僅當至少有一邊長度不同。

首先我們應當考慮三角形的性質。設三邊爲 x,y,zx,y,zx>y>zx>y>z.

則:

x<y+zx < y+z

可以得到 yy 的範圍:

xz<y<xx-z < y < x

假設 fxf_x 表示 xx 爲最長邊時的答案。

此時應存在:

fx=x(xz)1=z1f_x = x - (x-z) - 1 = z - 1

顯然這是已知 zz 的情況。zx2z \leq x-2,所以:

fx=z=1x2z1=z=1x1z=(x1)(x2)2f_x = \sum_{z=1}^{x-2} z-1 = \sum_{z=1}^{x-1} z = \frac{(x-1)(x-2)}{2}

但是你會發現這並不正確。y=zy=z 的情況需要剔除,這是一個簡單的容斥思想。

y=zy=z 時,顯然存在:

x2+1y=zx1\frac{x}{2} + 1 \leq y = z \leq x-1

所以這種情況的方案數爲:

(x1)(x2+1)=x22(x-1) - (\frac{x}{2} + 1) = \frac{x-2}{2}

考慮原來可能把 y=2,z=x1y=2 , z = x-1y=x1,z=2y=x-1 , z=2 重複計算,因此可得:

fx=(x1)(x2)2x222=(x2)24f_x = \frac{ \frac{(x-1)(x-2)}{2} - \frac{x-2}{2} }{2} =\frac{(x-2)^2}{4}

xx 爲自然數時應向下取整。

因此,若 gxg_x 表示題目所求,則:

{gx=0,x=1,2,3gx=gx1+fx,x>3\begin{cases} g_x = 0 , x=1,2,3 \\ g_x = g_{x-1} + f_x , x >3 \\ \end{cases}

以此類推即可。

時間複雜度:O(n+T)O(n+T). (TT 爲數據組數)

實際得分:100pts100pts.

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;

typedef __int128 ll;
const int N=1e6+1;

inline int read(){char ch=getchar(); int f=1; while(ch<'0' || ch>'9') {if(ch=='-') f=-f; ch=getchar();}
	int x=0; while(ch>='0' && ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return x*f;}

inline void write(ll x) {
	if(x<0) {putchar('-');write(-x);return;}
	if(x<10) {putchar(char(x%10+'0'));return;}
	write(x/10);putchar(char(x%10+'0'));
}

ll f[N]; int n;

int main() {
	f[1]=f[2]=f[3]=0ll;
	for(ll i=4;i<N;i++) f[i]=f[i-1]+(i-2)*(i-2)/4;
	while(1) {
		n=read(); if(n<3) return 0;
		write(f[n]); putchar('\n');
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章