In graph theory, graph colouring is a special case of graph labelling.
It is an assignment of labels traditionally called colours to edges of a graph.
Here we consider the simplest form.
Given an undirected simple complete graph G with n nodes, this problem asks
about a black-and-white edge-colouring of G, which contains the smallest total number of pure-coloured triangles.
A pure-coloured triangle in G is a set of three different nodes with three same-coloured edges between them.
Input Format
The input has several test cases and the first line provides the total number of test cases.
For each test case, a line with an integer n (n≤500) indicates that the given graph G is an undirected simple complete graph with n nodes.
Output Format
For each test case, output n+1 lines.
The first line contains the smallest number of pure-coloured triangles.
The following n lines describes an adjacent matrix A=(aij) of graph G.
The answer may not be unique and you can output anyone.
If the edge between i and j is white, aij and aji should be 1.
If the edge between i and j is black, aij and aji should be 2.
Elements of the main diagonal should be 0.
样例输入
2 3 6
样例输出
0 0 1 1 1 0 2 1 2 0 2 0 2 2 1 1 1 2 0 2 1 1 1 2 2 0 1 1 1 1 1 1 0 2 2 1 1 1 2 0 2 1 1 1 2 2 0
题目来源
分析:同色三元环数量最少等价于非同色三元环数量最多,而非同色三元环的数量等于共点的异色边对数量的一半,那么我们只要让异色边对尽量多就可以了,具体就是把每个点连出的一半边染1一半边染0,相当于给你n个点让你连边使得每个点的度数为(n-1)/2,这个过程可以贪心完成,即每次从当前未满足点向剩下点中度数最小的点连边,注意当n和(n-1)/2都是奇数的时候会有一个点的度数大于(n-1)/2,但这显然不影响答案。
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
int n,T,d[505],ans[505][505];
pii f[505];
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
cout<<n*(n-1)*(n-2)/6 - n*((n-1)/2)*(n-1-(n-1)/2)/2<<endl;
memset(d,0,sizeof(d));
memset(ans,0,sizeof(ans));
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++) f[j] = make_pair(d[j],j);
sort(f+1,f+1+n);
for(int j = 1;j <= n && d[i] < (n-1)/2;j++)
{
int t = f[j].second;
if(t == i) continue;
ans[i][t] = ans[t][i] = 1;
d[i]++,d[t]++;
}
}
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
if(j != n) cout<<( i == j ? 0 : ((ans[i][j] == 1) ? 1 : 2))<<" ";
else cout<<( i == j ? 0 : ((ans[i][j] == 1) ? 1 : 2))<<endl;
}
}