PAT A1053. Path of Equal Weight (30) [树的遍历]

Given a non-empty tree with root R, and with weight Wi assigned to each tree node Ti. The weight of a
path from R to L is defined to be the sum of the weights of all the nodes along the path from R to any leaf
node L.
Now given any weighted tree, you are supposed to find all the paths with their weights equal to a given
number. For example, let’s consider the tree showed in Figure 1: for each node, the upper number is the
node ID which is a two-digit number, and the lower number is the weight of that node. Suppose that the
given number is 24, then there exists 4 diferent paths which have the same given weight: {10 5 2 7}, {10 4
10}, {10 3 3 6 2} and {10 3 3 6 2}, which correspond to the red edges in Figure 1.
在这里插入图片描述
Input Specification:
Each input file contains one test case. Each case starts with a line containing 0 < N <= 100, the number of
nodes in a tree, M (< N), the number of non-leaf nodes, and 0 < S < 230, the given weight number. The
next line contains N positive numbers where Wi (<1000) corresponds to the tree node Ti. Then M lines
follow, each in the format:
ID K ID[1] ID[2] … ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children,
followed by a sequence of two-digit ID’s of its children. For the sake of simplicity, let us fix the root ID to
be 00.
Output Specification:
For each test case, print all the paths with weight S in non-increasing order. Each path occupies a line
with printed weights from the root to the leaf in order. All the numbers must be separated by a space with
no extra space at the end of the line.
Note: sequence {A1, A2, …, An} is said to be greater than sequence {B1, B2, …, Bm} if there exists 1 <= k <
min{n, m} such that Ai = Bi for i=1, … k, and Ak+1 > Bk+1
Sample Input:
20 9 24总结点数——非叶结点数——待判定权值
10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2按结点顺序Ti给出权值Wi
00 4 01 02 03 04结点ID——孩子数——孩子ID
02 1 05
04 2 06 07
03 3 11 12 13
06 1 09
07 2 08 10
16 1 15
13 3 14 16 17
17 2 18 19
Sample Output:
10 5 2 7
10 4 10
10 3 3 6 2
10 3 3 6 2
题⽬⼤意:给出树的结构和权值,找从根结点到叶⼦结点的路径上的权值相加之和等于给定⽬标数的
路径,并且从⼤到⼩输出路径
分析:对于接收孩⼦结点的数据时,每次完全接收完就对孩⼦结点按照权值进⾏排序(序号变,根据
权值变),这样保证深度优先遍历的时候直接输出就能输出从⼤到⼩的顺序。记录路径采取这样的⽅
式:⾸先建⽴⼀个path数组,传⼊⼀个nodeNum记录对当前路径来说这是第⼏个结点(这样直接在
path[nodeNum]⾥⾯存储当前结点的孩⼦结点的序号,这样可以保证在先判断return的时候, path是从
0~numNum-1的值确实是要求的路径结点)。然后每次要遍历下⼀个孩⼦结点的之前,令
path[nodeNum] = 孩⼦结点的序号,这样就保证了在return的时候当前path⾥⾯从0~nodeNum-1的值就
是要输出的路径的结点序号,输出这个序号的权值即可,直接在return语句⾥⾯输出。
注意:当sum==target的时候,记得判断是否孩⼦结点是空,要不然如果不空说明没有到底部,就直接
return⽽不是输出路径。。。(这对接下来的孩⼦结点都是正数才有⽤,负权⽆⽤)。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int target;
struct NODE {
	int w;
	vector<int> child;
	};
vector<NODE> v;
vector<int> path;
void dfs(int index, int nodeNum, int sum) {
	if(sum > target) return ;
	if(sum == target) {
		if(v[index].child.size() != 0) return;
		for(int i = 0; i < nodeNum; i++)
			printf("%d%c", v[path[i]].w, i != nodeNum - 1 ? ' ' : '\n');
		return ;
	}
	for(int i = 0; i < v[index].child.size(); i++) {
		int node = v[index].child[i];
		path[nodeNum] = node;
		dfs(node, nodeNum + 1, sum + v[node].w);
	}
}
int cmp1(int a, int b) {
	return v[a].w > v[b].w;
}
int main() {
	int n, m, node, k;
	scanf("%d %d %d", &n, &m, &target);
	v.resize(n), path.resize(n);
	for(int i = 0; i < n; i++)
		scanf("%d", &v[i].w);
	for(int i = 0; i < m; i++) {
		scanf("%d %d", &node, &k);
		v[node].child.resize(k);
		for(int j = 0; j < k; j++)
		scanf("%d", &v[node].child[j]);
		sort(v[node].child.begin(), v[node].child.end(), cmp1);
	}
	dfs(0, 1, v[0].w);
return 0;
}
import pandas as pd import os # 确认文件存在且路径正确 file_path = "D:\\社会网络分析\\期末\\智慧图书馆.xlsx" # 替换为你的实际文件名 print("文件是否存在:", os.path.exists(file_path)) # 应输出True # 尝试读取文件(根据实际格式选择) try: if file_path.endswith('.xlsx'): df = pd.read_excel(file_path) elif file_path.endswith('.csv'): df = pd.read_csv(file_path, encoding='utf-8') # 或 encoding='gbk' print("数据前5行:\n", df.head()) # 检查数据是否正常加载 except Exception as e: print("读取文件失败:", e) df = None # 明确标记为None from itertools import combinations # 生成作者合作边表 edges = [] for _, row in df.iterrows(): authors = row["authors"].split(",") if isinstance(row["authors"], str) else row["authors"] orgs = row["organizations"].split(",") if isinstance(row["organizations"], str) else row["organizations"] # 同一篇论文中的作者两两组合 for (a1, a2), (o1, o2) in zip(combinations(authors, 2), combinations(orgs, 2)): edges.append({ "Source": f"{a1.strip()} ({o1.strip()})", # 格式:作者 (机构) "Target": f"{a2.strip()} ({o2.strip()})", "Weight": 1 # 合作次数初始为1 }) # 合并重复边(累加权重) edges_df = pd.DataFrame(edges) edges_df = edges_df.groupby(["Source", "Target"], as_index=False).sum() # 保存边表 edges_df.to_csv("author_edges.csv", index=False)##--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[3], line 18 16 # 合并重复边(累加权重) 17 edges_df = pd.DataFrame(edges) ---> 18 edges_df = edges_df.groupby(["Source", "Target"], as_index=False).sum() 20 # 保存边表 21 edges_df.to_csv("author_edges.csv", index=False) File D:\信息计量学\python\.venv\Lib\site-packages\pandas\core\frame.py:9190, in DataFrame.groupby(self, by, axis, level, as_index, sort, group_keys, observed, dropna) 9187 if level is None and by is None: 9188 raise TypeError("You have to supply one of 'by' and 'level'") -> 9190 return DataFrameGroupBy( 9191 obj=self, 9192 keys=by, 9193 axis=axis, 9194 level=level, 9195 as_index=as_index, 9196 sort=sort, 9197 group_keys=group_keys, 9198 observed=observed, 9199 dropna=dropna, 9200 ) File D:\信息计量学\python\.venv\Lib\site-packages\pandas\core\groupby\groupby.py:1329, in GroupBy.__init__(self, obj, keys, axis, level, grouper, exclusions, selection, as_index, sort, group_keys, observed, dropna) 1326 self.dropna = dropna 1328 if grouper is None: -> 1329 grouper, exclusions, obj = get_grouper( 1330 obj, 1331 keys, 1332 axis=axis, 1333 level=level, 1334 sort=sort, 1335 observed=False if observed is lib.no_default else observed, 1336 dropna=self.dropna, 1337 ) 1339 if observed is lib.no_default: 1340 if any(ping._passed_categorical for ping in grouper.groupings): File D:\信息计量学\python\.venv\Lib\site-packages\pandas\core\groupby\grouper.py:1043, in get_grouper(obj, key, axis, level, sort, observed, validate, dropna) 1041 in_axis, level, gpr = False, gpr, None 1042 else: -> 1043 raise KeyError(gpr) 1044 elif isinstance(gpr, Grouper) and gpr.key is not None: 1045 # Add key to exclusions 1046 exclusions.add(gpr.key) KeyError: 'Source'
06-21
### 解决Pandas在执行groupby操作时出现的KeyError: 'Source'问题 在使用 `pandas.DataFrame.groupby` 方法时,如果遇到 `KeyError: 'Source'` 的错误,通常是因为指定的分组键(如 `'Source'`)在数据框中不存在或未被正确识别。以下是可能导致此问题的原因及解决方法: #### 1. 检查列名是否正确 确保数据框中确实存在名为 `'Source'` 的列。列名区分大小写,因此 `'source'` 和 `'Source'` 是不同的[^1]。可以通过以下代码检查列名: ```python print(df.columns) ``` 如果列名不匹配,请更正列名或指定正确的列名进行分组。 #### 2. 数据框中是否存在缺失值 如果数据框中存在缺失值,可能会导致分组失败。可以使用以下代码检查是否有缺失值: ```python print(df['Source'].isnull().sum()) ``` 如果有缺失值,可以考虑删除或填充这些值: ```python df = df.dropna(subset=['Source']) # 删除缺失值 # 或者 df['Source'] = df['Source'].fillna('Unknown') # 填充缺失值 ``` #### 3. 确保分组键为字符串类型 如果 `'Source'` 列的数据类型不是字符串,可能会引发问题。可以将该列转换为字符串类型: ```python df['Source'] = df['Source'].astype(str) ``` #### 4. 示例代码 以下是一个完整的示例,展示如何正确使用 `groupby` 并避免 `KeyError`: ```python import pandas as pd # 创建示例数据框 data = {'Source': ['A', 'B', 'C', 'A'], 'Value': [10, 20, 30, 40]} df = pd.DataFrame(data) # 确保列名正确 if 'Source' in df.columns: grouped = df.groupby('Source').sum() print(grouped) else: print("列 'Source' 不存在") ``` #### 5. 使用 `try-except` 捕获异常 如果不确定列名是否正确,可以使用 `try-except` 块捕获异常并输出调试信息: ```python try: result = df.groupby('Source').sum() print(result) except KeyError as e: print(f"KeyError: {e}. 请检查列名是否正确。") ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值