UVa 1510 Neon Sign

UVa 1510 Neon Sign

JungHeum recently opened a restaurant called ‘Triangle’ and has ordered the following neon sign for his
restaurant. The neon sign has N corners positioned on the circumference of a circle, and N ( N 1 ) / 2 N ∗ (N −1)/2 luminous tubes that connect the corners. There are only two colors for luminous tubes, red and blue.
JungHeum wants the sign to show only one shape of a triangle at a time, whose luminous tubes
colors are same, continuously. Hence, he wants to know the number of uni-color triangles.
For example, the following neon sign has only two uni-color triangles (1, 3, 5) and (2, 3, 4).
在这里插入图片描述
Given the number of corners of the neon sign and the colors of the luminous tubes in the sign, write
a program that finds the number of uni-color triangles.
Input
Your program is to read from standard input. The input consists of T test cases. The number of test
cases T is given in the first line of the input. Each test case starts with an integer N (3 ≤ N ≤ 1, 000),
which represents the number of corners of the neon sign. In the following N − 1 lines, the information
about the color of the luminous tubes are given. For the i-th line of these lines, the color information
of the luminous tubes that connect corner i to corners from corner i + 1 to N are given. Note that the
color red is represented as ‘1’ and the color blue is represented as ‘0’.

Output

Your program is to write to standard output. Print exactly one line for each test case. The line should
contain the number of uni-color triangles.
The following shows sample input and output for two test cases.

Sample Input

2
5
1 1 0 1
0 0 0
0 1
1
5
1 1 1 1
0 0 1
0 1
1

Sample Output

2
4

计数题,比较巧妙,直接考虑暴力就是 O ( n 3 ) O(n^3) 的复杂度,后来我试了试离散化到边,发现复杂度更高,后来发现其实很简单,三角形一共有 C n 3 C_n^3 种,对每个不符合条件的三角形,一定有两个点连接两条颜色不相同的边,那么即可计算出所有点不同的总数 s u m sum ,用总情况减去 s u m / 2 sum/2 即可,AC代码如下:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e3+5;

ll blue[N],red[N],n,k,t;
int main() {
    cin>>t;
    while(t--){
		cin>>n;
		fill(blue,blue+N,0);
		fill(red,red+N,0);
		for(ll i=1;i<=n;i++){
	        for(ll j=i+1;j<=n;j++){
	            cin>>k;
	            if(k==0) red[i]++,red[j]++;
	            else blue[i]++,blue[j]++;
	        }
		}
		ll sum=0;
		for(ll i=1;i<=n;i++)
	        sum+=blue[i]*red[i];
	    ll ans=n*(n-1)*(n-2)/6;
	    cout<<ans-sum/2<<endl;
	    }
	return 0;
}
发布了288 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43765333/article/details/104324189