CF976D. Degree Set

本文介绍了一种算法,用于构造一个无向图,其度数序列符合给定的正整数序列。该算法确保了图中没有自环和重边,且总边数不超过10^6。通过递归地解决子问题,最终输出满足条件的图的边集。

题目大意:

给你一个长度为 $n$ 的正整数序列 $d\_1, d\_2, ......, d\_n$ ( $d\_1 < d\_2 < ...... < d\_n$ )。要求你构造一个满足以下条件的无向图:

1. 有恰好 $d_n + 1$ 个点;
2. 没有自环;
3. 没有重边;
4. 总边数不超过 $10^6$ ;
5. 它的度数集合等于 $d$ 。

点从 $1$ 标号至 $d_n + 1$ 。

图的度数序列是一个长度与图的点数相同的数组 $a$ ,其中 $a_i$ 是第 $i$ 个顶点的度数(与其相邻的顶点数)。

图的度数集合是度数序列排序后去重的结果。

保证有解,要求输出符合条件的图。

思路:

对于对于前 $d[1]$ 个点向所有点连接一条边于是现在当前局面里有 $d[1]$ 个点为度数 $d[n]$ ,其余点度数为 $d[1]$ ,所以我们对于度数为 $d[n]$ 的 $d[1]$ 个点不再进行操作,对于度数为 $d[n]$ 的 $d[n]-d[n-1]$ 个点也不再操作。那么问题就转化成子问题,构造 $(d[2]-d[1],d[3]-d[1],......,d[n-1]-d[1])$ 的子问题。

以下代码:

#include<bits/stdc++.h>
#define il inline
#define _(d) while(d(isdigit(ch=getchar())))
using namespace std;
const int N=1e6+5;
int n,tot,cnt,d[N];
struct node{
    int x,y;
}t[N];
il int read(){
   int x,f=1;char ch;
   _(!)ch=='-'?f=-1:f;x=ch^48;
   _()x=(x<<1)+(x<<3)+(ch^48);
   return f*x;
}
il void ins(int x,int y){
    t[++tot]=(node){x,y};
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++)d[i]=read();
    int L=1,R=d[n]+1;
    for(int i=1,j=n;i<=(n>>1);i++,j--){
        for(int k=1;k<=d[i];k++)for(int l=L;l<R-k+1;l++)
            t[++tot]=(node){R-k+1,l};
        L+=d[j]-d[j-1];R-=d[i];
        for(int k=i+1;k<j;k++)d[k]-=d[i];
    }
    if(n&1){
        for(int i=L;i<=R;i++){
            for(int j=L;j<i;j++)t[++tot]=(node){i,j};
        }
    }
    printf("%d\n",tot);
    for(int i=1;i<=tot;i++)printf("%d %d\n",t[i].x,t[i].y);
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/Jessie-/p/10527906.html

import xarray as xr import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter from matplotlib.font_manager import FontProperties # 读取NetCDF文件 file_path = r"C:\1\wrfout_d03_2024-01-16" ds = xr.open_dataset(file_path) plt.rcParams['font.family'] = 'Times New Roman' # 全局默认字体(英文用) plt.rcParams['font.size'] = 18 # 提取变量 time_idx = 27 u10 = ds['U10'].isel(Time=time_idx) v10 = ds['V10'].isel(Time=time_idx) ws = np.sqrt(u10**2 + v10**2) # 获取经纬度 lat = ds['XLAT'].isel(Time=0).values lon = ds['XLONG'].isel(Time=0).values # 计算数据范围 lon_min, lon_max = lon.min(), lon.max() lat_min, lat_max = lat.min(), lat.max() # 计算数据范围大小 lon_range = lon_max - lon_min lat_range = lat_max - lat_min # 计算合适的刻度间隔 base_interval = min(lon_range, lat_range) / 5 tick_interval = max(round(base_interval * 100) / 100, 0.01) # 生成刻度值函数 def generate_ticks(min_val, max_val, interval): if interval <= 0: interval = 0.01 start = np.floor(min_val / interval) * interval end = np.ceil(max_val / interval) * interval num_points = int((end - start) / interval) + 1 if num_points > 100: interval *= 2 start = np.floor(min_val / interval) * interval end = np.ceil(max_val / interval) * interval ticks = np.arange(start, end + interval, interval) return np.round(ticks, 2) xticks = generate_ticks(lon_min, lon_max, tick_interval) yticks = generate_ticks(lat_min, lat_max, tick_interval) # 投影设置 proj = ccrs.PlateCarree() # 绘图设置 - 增加底部空间 fig = plt.figure(figsize=(12, 10)) # 增加高度为10,为底部标签留出空间 ax = fig.add_subplot(1, 1, 1, projection=proj) # 添加地理要素 ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.6) ax.add_feature(cfeature.BORDERS.with_scale('50m'), linewidth=0.6) ax.add_feature(cfeature.STATES.with_scale('50m'), linewidth=0.4) # 绘制风速填色图 cf = ax.contourf( lon, lat, ws, transform=proj, cmap='viridis', levels=np.linspace(0, 12, 13), extend='max' ) # 创建自定义字体属性 song_font = FontProperties(family='SimSun', size=22) # 宋体用于中文 times_font = FontProperties(family='Times New Roman', size=22) # Times New Roman用于英文 # 色标设置 - 放置在图片下方 cbar = plt.colorbar(cf, ax=ax, orientation='horizontal', pad=0.1, shrink=0.7) cbar_ax = cbar.ax # 清空默认标签 cbar.set_label('') # 标题和时间 time_str = ds.Times[time_idx].values.astype(str) plt.title(f'Surface Wind Speed\n{time_str}') # 设置地图范围 ax.set_extent([lon_min, lon_max, lat_min, lat_max], crs=proj) # 网格线和标签 gl = ax.gridlines( crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.5, color='gray', alpha=0.5, linestyle='--' ) # 设置刻度 gl.xlocator = plt.FixedLocator(xticks) gl.ylocator = plt.FixedLocator(yticks) # 标签设置 gl.top_labels = False gl.right_labels = False gl.bottom_labels = True gl.left_labels = True gl.xformatter = LongitudeFormatter(number_format='.2f', degree_symbol='°') gl.yformatter = LatitudeFormatter(number_format='.2f', degree_symbol='°') # 调整布局,为底部标签留出空间 plt.tight_layout(rect=[0, 0.1, 1, 0.95]) # 底部保留10%的空间 # 在图片正下方添加标签 # 使用图形坐标系统 (0,0) 左下角, (1,1) 右上角 label_x = 0.5 # 水平居中 label_y = 0.12 # 在图片底部上方 # 或者使用单一文本对象(更精确控制位置) # 计算中文部分宽度(近似) chinese_width = 0.01 # "风速"的近似宽度 # 添加组合标签 fig.text(label_x - chinese_width/2, label_y, '风速', fontproperties=song_font, ha='right', va='center') fig.text(label_x + chinese_width/2, label_y, '(m/s)', fontproperties=times_font, ha='left', va='center') plt.show() ds.close() 修改代码 把图名删了
07-25
import xarray as xr import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter from matplotlib.font_manager import FontProperties # 读取NetCDF文件 file_path = r"C:\1\wrfout_d03_2024-01-16" ds = xr.open_dataset(file_path) plt.rcParams['font.family'] = 'Times New Roman' # 全局默认字体(英文用) plt.rcParams['font.size'] = 16 # 提取变量 time_idx = 27 u10 = ds['U10'].isel(Time=time_idx) v10 = ds['V10'].isel(Time=time_idx) ws = np.sqrt(u10**2 + v10**2) # 获取经纬度 lat = ds['XLAT'].isel(Time=0).values lon = ds['XLONG'].isel(Time=0).values # 计算数据范围 lon_min, lon_max = lon.min(), lon.max() lat_min, lat_max = lat.min(), lat.max() # 计算数据范围大小 lon_range = lon_max - lon_min lat_range = lat_max - lat_min # 计算合适的刻度间隔 base_interval = min(lon_range, lat_range) / 5 tick_interval = max(round(base_interval * 100) / 100, 0.01) # 生成刻度值函数 def generate_ticks(min_val, max_val, interval): if interval <= 0: interval = 0.01 start = np.floor(min_val / interval) * interval end = np.ceil(max_val / interval) * interval num_points = int((end - start) / interval) + 1 if num_points > 100: interval *= 2 start = np.floor(min_val / interval) * interval end = np.ceil(max_val / interval) * interval ticks = np.arange(start, end + interval, interval) return np.round(ticks, 2) xticks = generate_ticks(lon_min, lon_max, tick_interval) yticks = generate_ticks(lat_min, lat_max, tick_interval) # 投影设置 proj = ccrs.PlateCarree() # 绘图设置 fig = plt.figure(figsize=(12, 9)) ax = fig.add_subplot(1, 1, 1, projection=proj) # 添加地理要素 ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.6) ax.add_feature(cfeature.BORDERS.with_scale('50m'), linewidth=0.6) ax.add_feature(cfeature.STATES.with_scale('50m'), linewidth=0.4) # 绘制风速填色图 cf = ax.contourf( lon, lat, ws, transform=proj, cmap='viridis', levels=np.linspace(0, 12, 13), extend='max' ) # 创建自定义字体属性 song_font = FontProperties(family='SimSun', size=20) # 宋体用于中文 times_font = FontProperties(family='Times New Roman', size=20) # Times New Roman用于英文 # 色标设置 cbar = plt.colorbar(cf, ax=ax, orientation='horizontal', pad=0.08, shrink=0.8) # 清空默认标签 cbar.set_label('') # 添加自定义标签 - 风速(宋体)和单位(Times New Roman) # 计算标签位置 cbar_ax = cbar.ax label_x = 0.5 # 水平居中 label_y = -1.2 # 在色标下方 # 添加中文部分(风速) cbar_ax.text(label_x, label_y, '风速', fontproperties=song_font, ha='center', va='top') # 添加单位部分(m/s) cbar_ax.text(label_x + 0.1, label_y, '(m/s)', fontproperties=times_font, ha='left', va='top') # 标题和时间 time_str = ds.Times[time_idx].values.astype(str) plt.title(f'Surface Wind Speed\n{time_str}') # 设置地图范围 ax.set_extent([lon_min, lon_max, lat_min, lat_max], crs=proj) # 网格线和标签 gl = ax.gridlines( crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.5, color='gray', alpha=0.5, linestyle='--' ) # 设置刻度 gl.xlocator = plt.FixedLocator(xticks) gl.ylocator = plt.FixedLocator(yticks) # 标签设置 gl.top_labels = False gl.right_labels = False gl.bottom_labels = True gl.left_labels = True gl.xformatter = LongitudeFormatter(number_format='.2f', degree_symbol='°') gl.yformatter = LatitudeFormatter(number_format='.2f', degree_symbol='°') plt.tight_layout() plt.show() ds.close() 修改这个代码,风速m/s放在图片正下方
07-25
* This example program shows how 128 images of the interior of a church can be * combined into a mosaic that covers a 360x130 degree view. The images were acquired * with a camera in which the exposure and white balance were set to automatic. * Therefore, there are very large brightness and color differences between the images. * Hence, adjust_mosaic_images is used to align the images radiometrically. * Furthermore, blending is used to hide the transitions between the individual * images that make up the mosaic. dev_update_off () dev_close_window () dev_open_window (0, 0, 978, 324, 'black', WindowHandle) dev_set_part (0, 0, 647, 1955) set_display_font (WindowHandle, 16, 'mono', 'true', 'false') dev_set_color ('yellow') set_tposition (WindowHandle, 20, 20) write_string (WindowHandle, 'Reading images...') * Read the 128 images that make up the mosaic. gen_empty_obj (Images) for J := 1 to 128 by 1 read_image (Image, 'panorama/sankt_martin_automatic_' + J$'03d') concat_obj (Images, Image, Images) endfor get_image_size (Image, Width, Height) * Construct the tuples that determine which images should be matched. The * mosaic images were acquired as 16 vertical strips of 8 images each. * For each image, we match the image below the current image in the same * strip and the image to the left of the current image in the adjacent strip. FF := [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8] TT := [2,9,3,10,4,11,5,12,6,13,7,14,8,15,16] From := [] To := [] for J := 0 to 15 by 1 From := [From,(FF - 1 + 8 * J) % 128 + 1] To := [To,(TT - 1 + 8 * J) % 128 + 1] endfor * Initialize the data that is required for the self-calibration. HomMatrices2D := [] Rows1 := [] Cols1 := [] Rows2 := [] Cols2 := [] NumMatches := [] for J := 0 to |From| - 1 by 1 * Select the images to match. select_obj (Images, ImageF, From[J]) select_obj (Images, ImageT, To[J]) * Perform the point extraction of the images. points_foerstner (ImageF, 1, 2, 3, 50, 0.1, 'gauss', 'true', RowsF, ColsF, CoRRJunctions, CoRCJunctions, CoCCJunctions, RowArea, ColumnArea, CoRRArea, CoRCArea, CoCCArea) points_foerstner (ImageT, 1, 2, 3, 50, 0.1, 'gauss', 'true', RowsT, ColsT, CoRRJunctions1, CoRCJunctions1, CoCCJunctions1, RowArea1, ColumnArea1, CoRRArea1, CoRCArea1, CoCCArea1) concat_obj (ImageT, ImageF, ImageTF) tile_images_offset (ImageTF, TiledImage, [0,0], [0,Width + 20], [-1,-1], [-1,-1], [-1,-1], [-1,-1], 2 * Width + 20, Height) gen_cross_contour_xld (PointsF, RowsF, ColsF + Width + 20, 6, rad(45)) gen_cross_contour_xld (PointsT, RowsT, ColsT, 6, rad(0)) * Convert the images to gray value images. rgb1_to_gray (ImageF, ImageFG) rgb1_to_gray (ImageT, ImageTG) * Determine the projective transformation between the images. proj_match_points_ransac (ImageFG, ImageTG, RowsF, ColsF, RowsT, ColsT, 'ncc', 10, 0, 0, 648, 968, [rad(-10),rad(40)], 0.5, 'gold_standard', 10, 42, HomMat2D, Points1, Points2) * After this, we accumulate the required data. HomMatrices2D := [HomMatrices2D,HomMat2D] Rows1 := [Rows1,subset(RowsF,Points1)] Cols1 := [Cols1,subset(ColsF,Points1)] Rows2 := [Rows2,subset(RowsT,Points2)] Cols2 := [Cols2,subset(ColsT,Points2)] NumMatches := [NumMatches,|Points1|] * The rest of the code within the loop visualizes the point matches. RF := subset(RowsF,Points1) CF := subset(ColsF,Points1) + Width + 20 RT := subset(RowsT,Points2) CT := subset(ColsT,Points2) gen_empty_obj (Matches) for K := 0 to |RF| - 1 by 1 gen_contour_polygon_xld (Match, [RF[K],RT[K]], [CF[K],CT[K]]) concat_obj (Matches, Match, Matches) endfor dev_clear_window () dev_display (TiledImage) dev_set_color ('blue') dev_display (Matches) dev_set_color ('green') dev_display (PointsF) dev_display (PointsT) dev_set_color ('yellow') set_tposition (WindowHandle, 20, 20) write_string (WindowHandle, 'Matches between images ' + From[J]$'d' + ' and ' + To[J]$'d') endfor dev_clear_window () dev_set_window_extents (-1, -1, 856, 428) dev_set_color ('yellow') set_tposition (WindowHandle, 20, 20) write_string (WindowHandle, 'Performing self-calibration...') * Perform the self-calibration. stationary_camera_self_calibration (128, 968, 648, 6, From, To, HomMatrices2D, Rows1, Cols1, Rows2, Cols2, NumMatches, 'gold_standard', ['focus','principal_point','kappa'], 'true', CameraMatrix, Kappa, RotationMatrices, X, Y, Z, Error) dev_clear_window () dev_set_color ('yellow') set_tposition (WindowHandle, 20, 20) write_string (WindowHandle, 'Removing radial distortions...') * Remove the radial distortions from the images. cam_mat_to_cam_par (CameraMatrix, Kappa, 968, 648, CamParam) change_radial_distortion_cam_par ('fixed', CamParam, 0, CamParOut) gen_radial_distortion_map (Map, CamParam, CamParOut, 'bilinear') map_image (Images, Map, Images) dev_clear_window () dev_set_color ('yellow') set_tposition (WindowHandle, 20, 20) write_string (WindowHandle, 'Adjusting the images radiometrically...') * Before we adjust the images radiometrically, we compute the perspective * transformations between the images from the camera matrix and the rotation * matrices that are returned by the self-calibration. They are more accurate * than the perspective transformations that are returned by the matching * since they have been optimized over all images. For details on how the * perspective transformation matrices are computed by the code below, see the * documentation of stationary_camera_self_calibration. hom_mat2d_invert (CameraMatrix, CameraMatrixInv) PermMat := [0.0,1.0,0.5,1.0,0.0,0.5,0.0,0.0,1.0] hom_mat2d_invert (PermMat, PermMatInv) hom_mat2d_compose (CameraMatrixInv, PermMatInv, CamMatPermInv) hom_mat2d_compose (PermMat, CameraMatrix, CamMatPerm) HomMats2D := [] for J := 0 to |From| - 1 by 1 RotMatFrom := RotationMatrices[9 * (From[J] - 1):9 * (From[J] - 1) + 8] RotMatTo := RotationMatrices[9 * (To[J] - 1):9 * (To[J] - 1) + 8] hom_mat2d_transpose (RotMatFrom, RotMatFromInv) hom_mat2d_compose (RotMatTo, RotMatFromInv, RotMat) hom_mat2d_compose (RotMat, CamMatPermInv, RotCamMatInv) hom_mat2d_compose (CamMatPerm, RotCamMatInv, HomMat2D) HomMats2D := [HomMats2D,HomMat2D] endfor * Now adjust the images radiometrically. Since the exposure and white balance * were set to automatic, we calculate 'mult_gray'. Since the camera is a consumer * camera and therefore has a highly nonlinear response, we compute 'response'. * To compensate the vignetting in the images, we compute 'vignetting'. Finally, * to speed up the optimization, we use a subsampling by a factor of 4. adjust_mosaic_images (Images, CorrectedImages, From, To, 118, HomMats2D, 'gold_standard', ['mult_gray','response','vignetting','subsampling_4'], 'laguerre') * Since the reference image was not aligned perfectly horizontally, we modify the * calibrated rotation matrices by rotating them by -5.5 degrees around the x axis. hom_mat3d_identity (HomMat3D) hom_mat3d_rotate (HomMat3D, rad(-5.5), 'x', 0, 0, 0, HomMat3D) RotMat := [HomMat3D[0:2],HomMat3D[4:6],HomMat3D[8:10]] RotMats := [] for J := 0 to 127 by 1 RotMatCalib := RotationMatrices[J * 9:J * 9 + 8] hom_mat2d_compose (RotMatCalib, RotMat, RotMatRot) RotMats := [RotMats,RotMatRot] endfor dev_clear_window () dev_set_color ('yellow') set_tposition (WindowHandle, 20, 20) write_string (WindowHandle, 'Creating spherical mosaic of the original images...') * Create the spherical mosaic of the original images. gen_spherical_mosaic (Images, SphericalMosaicOrig, CameraMatrix, RotMats, -90, 90, -180, 180, 0, 'voronoi', 'bilinear') get_image_size (SphericalMosaicOrig, Width, Height) dev_set_part (0, 0, Height - 1, Width - 1) dev_clear_window () dev_display (SphericalMosaicOrig) dev_set_color ('yellow') set_tposition (WindowHandle, Height - 300, 20) write_string (WindowHandle, 'Spherical mosaic of the original images') set_tposition (WindowHandle, Height - 150, 20) write_string (WindowHandle, 'Press \'Run\' to continue') stop () dev_clear_window () dev_set_color ('yellow') set_tposition (WindowHandle, 20, 20) write_string (WindowHandle, 'Creating spherical mosaic of the radiometrically adjusted images...') * Create the spherical mosaic of the radiometrically adjusted images. gen_spherical_mosaic (CorrectedImages, SphericalMosaicAdjust, CameraMatrix, RotMats, -90, 90, -180, 180, 0, 'voronoi', 'bilinear') get_image_size (SphericalMosaicAdjust, Width, Height) dev_set_part (0, 0, Height - 1, Width - 1) dev_clear_window () dev_display (SphericalMosaicAdjust) dev_set_color ('yellow') set_tposition (WindowHandle, Height - 300, 20) write_string (WindowHandle, 'Spherical mosaic of the radiometrically adjusted images') set_tposition (WindowHandle, Height - 150, 20) write_string (WindowHandle, 'Press \'Run\' to continue') stop () dev_clear_window () dev_set_color ('yellow') set_tposition (WindowHandle, 20, 20) write_string (WindowHandle, 'Creating blended spherical mosaic of the radiometrically adjusted images...') * Create the blended spherical mosaic of the radiometrically adjusted images. gen_spherical_mosaic (CorrectedImages, SphericalMosaicAdjustBlend, CameraMatrix, RotMats, -90, 90, -180, 180, 0, 'blend', 'bilinear') get_image_size (SphericalMosaicAdjustBlend, Width, Height) dev_set_part (0, 0, Height - 1, Width - 1) dev_clear_window () dev_display (SphericalMosaicAdjustBlend) dev_set_color ('yellow') set_tposition (WindowHandle, Height - 300, 20) write_string (WindowHandle, 'Blended spherical mosaic of the radiometrically adjusted images')
06-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值