列表

详情


NC24953. [USACO 2008 Jan G]Cell Phone Network

描述

Farmer John has decided to give each of his cows a cell phone in hopes to encourage their social interaction. This, however, requires him to set up cell phone towers on his N (1 ≤ N ≤ 10,000) pastures (conveniently numbered 1..N) so they can all communicate.
Exactly N-1 pairs of pastures are adjacent, and for any two pastures A and B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B) there is a sequence of adjacent pastures such that A is the first pasture in the sequence and B is the last. Farmer John can only place cell phone towers in the pastures, and each tower has enough range to provide service to the pasture it is on and all pastures adjacent to the pasture with the cell tower.
Help him determine the minimum number of towers he must install to provide cell phone service to each pasture.

输入描述

* Line 1: A single integer: N
* Lines 2..N: Each line specifies a pair of adjacent pastures with two space-separated integers: A and B

输出描述

* Line 1: A single integer indicating the minimum number of towers to install

示例1

输入:

5
1 3
5 2
4 3
3 5

输出:

2

说明:

The towers can be placed at pastures 2 and 3 or pastures 3 and 5.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++(g++ 7.5.0) 解法, 执行用时: 6ms, 内存消耗: 960K, 提交时间: 2023-02-18 22:27:15

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

constexpr int inf=0x3f;
int ans;
int vis[10005];
vector<int> e[10005];
void dfs(int u,int fa)
{
    int flag=0;
    for(auto v:e[u])
    {
        if(v==fa) continue;
        dfs(v,u);
        flag|=vis[v];
    }
    if(!flag&&!vis[u]&&!vis[fa])
    {
        vis[fa]=1,ans++;
    }
}

int main()
{
    ios::sync_with_stdio(0);
    int n;
    cin>>n;
    for(int i=1;i<=n;++i)
    {
        int x,y;
        cin>>x>>y;
        e[x].push_back(y);
        e[y].push_back(x);
    }
    dfs(1,0);
    cout<<ans;
    return 0;
}

C++11(clang++ 3.9) 解法, 执行用时: 12ms, 内存消耗: 1096K, 提交时间: 2020-03-29 13:22:23

#include<bits/stdc++.h>
using namespace std;
int n,ans=0;
vector<int>f[20010];
int dfs(int u,int p)
{
	int ch=-1;
	for(int i=0;i<f[u].size();i++)
	{
		int val=f[u][i];
		if(val!=p)
		{
			int ret=dfs(val,u);
			if(ret==-1) ch=1;
			else if(ret==1&&ch!=1) ch=0;
		}
	}
	if(ch==1) ans++;
	return ch;
}
int main()
{
	cin>>n;
	for(int i=1;i<n;i++)
	{
		int a,b;
		cin>>a>>b;
		f[a].push_back(b);
		f[b].push_back(a);
	}
	if(dfs(1,0)==-1) ans++;
	cout<<ans<<"\n";
	return 0;
}

上一题