链接
题目
题意:
就是给你n个数,叫你构造出所有点不相对应的组合。
解法:
假设成功补全所有f[i].
i|1~n均出现且只出现一次 --> 所有点出度为1
f|1~n均出现且只出现一次 --> 所有点入度为1
==> 补全后图形为若干个环, 称为环图.
#include<iostream>
#include<cstring>
using namespace std;
const int N=210010;
int e[N],ne[N]; //ne[i]存的是第i个元素的属性值,e[i]存的是i的上标值。
bool st[N];
int main()
{
int t;
cin>>t;
while(t--)
{
int n,flag=1;
scanf("%d",&n);
memset(e,0,sizeof e);
memset(ne,0,sizeof ne);
memset(st,0,sizeof st);
for(int i=1; i<=n; i++)
{
scanf("%d",&ne[i]); //输入第i个的属性值,然后标记其上标值。
e[ne[i]]=i;
}
for(int i=1; i<=n; i++)
{
if(!ne[i]||st[i])continue; //如果这个点的ne没有值的话没有办法相连,或者是这个点已近使用过了。
st[i]=true;
int x=i,y=i;
while(ne[x]&&!st[ne[x]]) //找到最后的点并标记已经用过的点
{
x=ne[x];
st[x]=true;
}
while(e[y]&&!st[e[y]]) //找到最开始的点并标记已经用过的点
{
y=e[y];
st[y]=true;
}
if(ne[x]==y)continue; //如果成环那么退出
if(flag==1) //如果不成环的话需要加入其他没有在环上的点。
{
flag=0;
for (int j = 1; j <= n; j ++ )
if (!e[j] && !ne[j])
{
st[j] = true;
ne[x] = j;
x = j;
}
}
ne[x]=y; //所有的点都在环上了,首尾相连
}
if (flag==1) //将没有在环上的点,单独构成一个环
{
int x = 0, y = 0;
for (int i = 1; i <= n; i ++ )
if (!ne[i])
{
if (!x && !y) x = y = i;
else
{
ne[x] = i;
x = i;
}
}
ne[x] = y;
}
for (int i = 1; i <= n; i ++ )
printf("%d ", ne[i]);
cout<<endl;
}
return 0;
}