Codeforces Round #677 D. Districts Connection

本文介绍了一种算法,该算法在给定点集的情况下,根据特定条件(如避免同帮派节点相连)构建一棵树。通过使用暴力方法并跟踪已连接节点,确保最终结构符合要求。

题目

题意:给出n个点,对n个点连n-1条边要求构成一棵树,其中对于树中属于同一帮派的点不能相互连边。则我们只需对所有的点进行连边尝试,直到连了n-1条边即可。遇到同一个帮派的点或已经连接的点直接跳过即可。(题目数据不大直接暴力就过了)

AC code

    #include<iostream>
    #include<string>
    #include<map>
    #include<algorithm>
    #include<memory.h>
    #include<cmath>
    #define pii pair<int,int>
    #define FAST ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
    using namespace std;
    typedef long long ll;
    const int Max = 1e6 + 5;
    int lst[Max];
    int ls[Max][2];
     
    int main()
    {
    	FAST;
    	int t;cin >>t;
    	while (t--)
    	{
    		map<int, int> ma;//ma用来标记哪些点已经连接
    		int n;cin >> n;
    		for (int i = 1;i <= n;i++)cin >> lst[i];
    		int g = 0;
    		for (int i = 1;i <= n;i++)
    		{
    			for (int j = 1;j <= n;j++)
    			{
    				if (g == n - 1)break;//已连n-1条边
    				if (ma[i]&&ma[j])//两点已在
    				{
    					continue;
    				}
    				else
    				{
    					if (lst[i] == lst[j])continue;//相同帮派跳过
    					else
    					{
    						ma[i]++,ma[j]++;
    						ls[++g][0] = i, ls[g][1] = j;
    					}
    				}
    			}
    		}
    		if (g != n - 1)
    			cout << "NO" << endl;
    		else
    		{
    			cout << "YES" << endl;
    			for (int i = 1;i <= g;i++)cout << ls[i][0] << " " << ls[i][1] << endl;
    		}
    		
    	}
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Rikka_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值