Transmitters(简单几何)

该博客详细介绍了POJ 1106题目的解决方案,主要涉及数学和几何知识。内容包括题目的描述、输入输出格式以及样例分析,适合对算法和几何感兴趣的读者深入研究。
Transmitters
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 4617 Accepted: 2468

题目链接:http://poj.org/problem?id=1106


Description

In a wireless network with multiple transmitters sending on the same frequencies, it is often a requirement that signals don't overlap, or at least that they don't conflict. One way of accomplishing this is to restrict a transmitter's coverage area. This problem uses a shielded transmitter that only broadcasts in a semicircle.

A transmitter T is located somewhere on a 1,000 square meter grid. It broadcasts in a semicircular area of radius r. The transmitter may be rotated any amount, but not moved. Given N points anywhere on the grid, compute the maximum number of points that can be simultaneously reached by the transmitter's signal. Figure 1 shows the same data points with two different transmitter rotations.

All input coordinates are integers (0-1000). The radius is a positive real number greater than 0. Points on the boundary of a semicircle are considered within that semicircle. There are 1-150 unique points to examine per transmitter. No points are at the same location as the transmitter.

Input

Input consists of information for one or more independent transmitter problems. Each problem begins with one line containing the (x,y) coordinates of the transmitter followed by the broadcast radius, r. The next line contains the number of points N on the grid, followed by N sets of (x,y) coordinates, one set per line. The end of the input is signalled by a line with a negative radius; the (x,y) values will be present but indeterminate. Figures 1 and 2 represent the data in the first two example data sets below, though they are on different scales. Figures 1a and 2 show transmitter rotations that result in maximal coverage.

Output

For each transmitter, the output contains a single line with the maximum number of points that can be contained in some semicircle.

Sample Input

25 25 3.5
7
25 28
23 27
27 27
24 23
26 23
24 29
26 29
350 200 2.0
5
350 202
350 199
350 198
348 200
352 200
995 995 10.0
4
1000 1000
999 998
990 992
1000 999
100 100 -2.5

Sample Output

3
4
4

Source

Mid-Central USA 2001

题目意思: 在一个二维平面上,有一个半圆和一些点,半圆可以绕圆心以任意方向旋转,问它最多可以包含几个点;

意解: 首先筛除掉点在圆外的点,把在圆内的点放进p数组,然后极角排序,从小到大;最后确定一个起始点,做半圆,求出包含的点;

AC代码:
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;
const int M = 500;
const double pi = acos(-1.0);
double p[M];
const double eps=1e-8;

double pow1(double a,double b)
{
    return (a - b) * (a - b);
}

double dist(double x1,double y1,double x2,double y2)
{
    return pow1(y2,y1) + pow1(x2,x1);
}

double Atan2(double x1,double y1,double x2,double y2)
{
    double x = x2 - x1;
    double y = y2 - y1;
    return atan2(y,x);//求出极角
}

int main()
{
   // freopen("in","r",stdin);
    double a,b,r,x,y;
    while(~scanf("%lf %lf %lf",&a,&b,&r) && r > eps)
    {
        int m,to,Max;
        scanf("%d",&m);
        to = Max = 0;
        while(m--)
        {
            scanf("%lf %lf",&x,&y);
            if(dist(x,y,a,b) > r * r) continue;
            p[to++] = Atan2(a,b,x,y);
            if(p[to - 1] < eps) p[to - 1] += 2 * pi;
        }
        sort(p,p + to);
        for(int i = to; i < to * 2; i++)
        {
            p[i] = p[i - to]+2*pi; //方便下面的处理;
        }
        for(int i = 0; i < to; i++)
        {
            int t = 1;
            for(int j = i + 1; j < to * 2; j++)
            {
                double ang=p[j]-p[i];
                if(ang>pi) break;
                t++;
            }
            Max = max(Max, t);
        }
        printf("%d\n",Max);
    }
    return 0;
}


将下述两段代码相结合,完成第一个大问题 def resection_position(fy00_pos, fy01_pos, fy02_pos, angle1, angle2): """ 使用后方交会方法计算无人机位置 :param fy00_pos: FY00的位置 :param fy01_pos: FY01的位置 :param fy02_pos: FY02的位置 :param angle1: 与FY01的连线和基准线的夹角(弧度) :param angle2: 与FY02的连线和基准线的夹角(弧度) :return: 计算出的无人机位置 """ def equations(p): x, y = p # 计算与FY00的连线向量 vec0 = np.array([x - fy00_pos[0], y - fy00_pos[1]]) norm_vec0 = np.linalg.norm(vec0) # 计算与FY01的连线向量 vec1 = np.array([x - fy01_pos[0], y - fy01_pos[1]]) # 计算两个向量之间的夹角 cos_angle1 = np.dot(vec0, vec1) / (norm_vec0 * np.linalg.norm(vec1)) error1 = np.arccos(np.clip(cos_angle1, -1.0, 1.0)) - angle1 # 计算与FY02的连线向量 vec2 = np.array([x - fy02_pos[0], y - fy02_pos[1]]) # 计算两个向量之间的夹角 cos_angle2 = np.dot(vec0, vec2) / (norm_vec0 * np.linalg.norm(vec2)) error2 = np.arccos(np.clip(cos_angle2, -1.0, 1.0)) - angle2 return [error1, error2] # 初始猜测位置 x0 = (fy00_pos[0] + fy01_pos[0] + fy02_pos[0]) / 3 y0 = (fy00_pos[1] + fy01_pos[1] + fy02_pos[1]) / 3 # 解方程 result = least_squares(equations, [x0, y0]) return result.x # 测试定位模型 fy00_pos = np.array([0, 0]) fy01_pos = np.array([100, 0]) fy02_pos = np.array([100 * np.cos(2*np.pi/9), 100 * np.sin(2*np.pi/9)]) # 假设接收信号的无人机位置为(80, 50) actual_pos = np.array([80, 50]) # 计算应接收到的角度信息 vec0 = actual_pos - fy00_pos vec1 = actual_pos - fy01_pos vec2 = actual_pos - fy02_pos # 计算角度 cos_angle1 = np.dot(vec0, -fy01_pos) / (np.linalg.norm(vec0) * np.linalg.norm(fy01_pos)) angle1 = np.arccos(np.clip(cos_angle1, -1.0, 1.0)) cos_angle2 = np.dot(vec0, vec2) / (np.linalg.norm(vec0) * np.linalg.norm(vec2)) angle2 = np.arccos(np.clip(cos_angle2, -1.0, 1.0)) # 使用定位模型计算位置 calculated_pos = resection_position(fy00_pos, fy01_pos, fy02_pos, angle1, angle2) print(f"实际位置: {actual_pos}") print(f"计算位置: {calculated_pos}") print(f"误差: {np.linalg.norm(actual_pos - calculated_pos):.2f}m") import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from scipy.optimize import minimize from scipy.optimize import least_squares # 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 将极坐标转化为直角坐标(弧度制) def function_a(rho, theta): x = rho * np.cos(theta) y = rho * np.sin(theta) return np.array([x, y]) # 将直角坐标转化为极坐标 def function_b(x, y): rho = np.sqrt(x**2 + y**2) theta = np.arctan2(y, x) return np.array([rho, theta if theta >= 0 else theta + 2 * np.pi]) # 两向量夹角(弧度制) def angle(v1, v2): dot_product = np.dot(v1, v2) length_v1 = np.linalg.norm(v1) length_v2 = np.linalg.norm(v2) if length_v1 == 0 or length_v2 == 0: return 0.0 ratio = dot_product / (length_v1 * length_v2) clipped_ratio = np.clip(ratio, -1, 1) angle = np.arccos(clipped_ratio) return angle #1 #二维三边测量 """ 对于最小二乘形式的目标函数 (最终使用)least_squares算法,收敛更快、稳定性更高,非线性最小二乘问题 minimize算法,收敛速度慢,对初始值敏感。 """ def trilateration_2d(beacons, distances): def residuals(p): x, y = p return [np.sqrt((x - bx)**2 + (y - by)**2) - d for (bx, by), d in zip(beacons, distances)] # 初始猜测位置,信标点的平均位置 x0 = np.mean([b[0] for b in beacons], axis=0) y0 = np.mean([b[1] for b in beacons], axis=0) result = least_squares(residuals, [x0, y0], loss='soft_l1') return result.x def localization_model(fy00_pos, other_drones, angles): # 构建观测方程 observations = [] for angle in angles: direction = np.array([np.cos(np.radians(angle)), np.sin(np.radians(angle))]) observations.append((fy00_pos, direction)) # 使用非线性最小二乘法求解最优位置 def cost_function(pos): error = 0 for fy_pos, direction in observations: vec = pos - fy_pos unit_vec = vec / np.linalg.norm(vec) error += np.arccos(np.dot(unit_vec, direction)) return error # 初始估计位置 initial_guess = np.mean([fy00_pos] + other_drones, axis=0) result = minimize(cost_function, initial_guess) return result.x # 等分角度 def generate_even_angles(n=9): return [2 * np.pi * i / n for i in range(n)] def draw_angle(ax, center, p1, p2, radius=0.3, color='blue', fontsize=8): angle1 = np.degrees(np.arctan2(p1[1], p1[0])) angle2 = np.degrees(np.arctan2(p2[1], p2[0])) mid_angle = np.radians((angle1 + angle2) / 2) label_x = center[0] + radius * 1.5 * np.cos(mid_angle) label_y = center[1] + radius * 1.5 * np.sin(mid_angle) ax.text(label_x, label_y, f"{abs(angle1 - angle2):.1f}°", fontsize=fontsize, color=color) def visualize_circular_formation(fy00_pos, directions, show_angles=True): fig, ax = plt.subplots(figsize=(8, 8)) line_color = 'gray' node_colors = plt.cm.tab10(np.linspace(0, 1, len(directions))) drone_positions = [fy00_pos + vec for vec in directions] for i, (vec, color) in enumerate(zip(directions, node_colors)): ax.plot([fy00_pos[0], vec[0]], [fy00_pos[1], vec[1]], color=line_color, linestyle='--', linewidth=1) pos = fy00_pos + vec ax.scatter(pos[0], pos[1], color=color, label=f"无人机{i+1}", s=100, edgecolor='black') ax.text(pos[0] + 0.03, pos[1] + 0.03, f"{i+1}", fontsize=10, color='black') if show_angles: for i in range(len(drone_positions)): p1 = drone_positions[i] - fy00_pos p2 = drone_positions[(i + 1) % len(drone_positions)] - fy00_pos draw_angle(ax, fy00_pos, p1, p2, radius=0.5, color='blue') ax.set_xlim(-1.5, 1.5) ax.set_ylim(-1.5, 1.5) ax.axhline(0, color='black', linewidth=0.5) ax.axvline(0, color='black', linewidth=0.5) ax.set_title("无人机圆形编队", fontsize=14) ax.legend(loc='upper right', bbox_to_anchor=(1.1, 1), fontsize=10) ax.grid(True, linestyle=':') ax.axis('equal') plt.tight_layout() plt.show() if __name__ == "__main__": angles_rad = generate_even_angles(n=9) print("生成的9个等分角度(弧度):") for i, a in enumerate(angles_rad): print(f"角度 {i+1}: {np.degrees(a):.2f}°") directions = [function_a(1.0, theta) for theta in angles_rad] visualize_circular_formation(np.array([0, 0]), directions, show_angles=True) #2 def min_drones_num(): return 3 def calculate_min_required_positions(known_drones, unknown_drones): if len(known_drones) >= 3: return 0 required = 3 - len(known_drones) if required <= 0: return 0 elif required <= len(unknown_drones): return required else: return len(unknown_drones) #3 def adjust_positions(initial_positions,max_iterations=100,tolerance=1e-6): fy00_pos=initial_positions[0] fy_positions = initial_positions[1:] # 将极坐标转换为笛卡尔坐标 cartesian_positions = [] for r, theta in fy_positions: x = r * np.cos(np.radians(theta)) y = r * np.sin(np.radians(theta)) cartesian_positions.append(np.array([x, y])) adjustment_process=[] for iteration in range(max_iterations): # 保存当前状态 current_state = { 'fy00': fy00_pos.copy(), 'drones': [pos.copy() for pos in cartesian_positions] } adjustment_process.append(current_state) # 计算理想圆的参数 ideal_radius = np.mean([np.linalg.norm(pos - fy00_pos) for pos in cartesian_positions]) # 理想位置 ideal_positions = [] for i in range(len(cartesian_positions)): angle = 2 * np.pi * i / len(cartesian_positions) ideal_x = fy00_pos[0] + ideal_radius * np.cos(angle) ideal_y = fy00_pos[1] + ideal_radius * np.sin(angle) ideal_positions.append(np.array([ideal_x, ideal_y])) # 计算误差 error = 0 for i in range(len(cartesian_positions)): error += np.linalg.norm(cartesian_positions[i] - ideal_positions[i]) # 检查是否收敛 if error < tolerance: print(f"Converged after {iteration} iterations") break # 更新位置 - 这里使用简单的线性调整策略 # 实际应用中可能需要更复杂的更新规则 for i in range(len(cartesian_positions)): direction = ideal_positions[i] - cartesian_positions[i] cartesian_positions[i] += 0.5 * direction # 使用0.5作为学习率 return { 'final_positions': cartesian_positions, 'adjustment_process': adjustment_process } def optimize_transmitter_selection(drones, fy00_index=0, max_transmitters=4): """ 优化发射信号的无人机选择 :param drones: 无人机位置列表 :param fy00_index: 圆心无人机的索引 :param max_transmitters: 最大允许的发射机数量 :return: 每次调整选择的发射机列表 """ # 策略:每次选择FY00和圆周上最多3架无人机发射信号 # 总调整次数 total_adjustments = 3 # 假设需要3次调整 # 选择发射机的策略 transmitter_choices = [] # 选择圆周上的无人机索引 peripheral_drones = [i for i in range(len(drones)) if i != fy00_index] # 第一次调整:选择均匀分布的4架无人机(包括FY00) first_choice = [fy00_index] + np.random.choice(peripheral_drones, 3, replace=False).tolist() transmitter_choices.append(first_choice) # 第二次调整:选择不同位置的无人机 remaining_drones = [i for i in peripheral_drones if i not in first_choice] second_choice = [fy00_index] + np.random.choice(remaining_drones, 3, replace=False).tolist() transmitter_choices.append(second_choice) # 第三次调整:使用所有可用信息 third_choice = [fy00_index] + peripheral_drones[:3] transmitter_choices.append(third_choice) return transmitter_choices
08-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值