这个代码为什么超时
查看原帖
这个代码为什么超时
868445
HeCao楼主2025/1/19 08:25
#include<bits/stdc++.h>
using namespace std;
int n,k,ans = 0;
const int maxn = 1e5 + 10;
int dist[maxn],dp[maxn],pre[maxn];
struct node{
	int to,w;
};
vector < node > edge[maxn];
map < int ,map < int,int > > mp;
int A,B,sum = 0;
void dfs1(int u,int fa) {
	for (int i = 0; i < edge[u].size(); i++) {
		int v = edge[u][i].to;
		if(v != fa) {
			dist[v] = dist[u] + edge[u][i].w;
			if(dist[v] > sum) {
				A = v;
				sum = dist[v];
			}
			dfs1(v,u);
		}
	}
}
void dfs2(int u,int fa) {
	for (int i = 0; i < edge[u].size(); i++) {
		int v = edge[u][i].to;
		if(v != fa) {
			dist[v] = dist[u] + edge[u][i].w;
			if(dist[v] > sum) {
				B = v;
				sum = dist[v];
				pre[v] = u;
			}
			dfs2(v,u);
		}
	}
}
void dfs3(int u,int fa) {
	for (int i = 0; i < edge[u].size(); i++) {
		int v= edge[u][i].to;
		if(v != fa) {
			dfs3(v,u);
			ans = max(ans,dp[u] + dp[v] + edge[u][i].w + mp[u][v]);
			dp[u] = max(dp[u],dp[v] + edge[u][i].w + mp[u][v]); 
		}
	}
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> n >> k;
	for (int i = 1; i < n; i++) {
		int u,v;
		cin >> u >> v;
		edge[u].push_back((node){v,1});
		edge[v].push_back((node){u,1}); 
	}
	if (k == 1) {
		dfs1(1,0);
		sum = 0;
		memset(dist,0,sizeof(dist));
		dfs2(A,0);
		cout << (n - 1) * 2 - dist[B] + 1 << "\n";
	}
	if (k == 2) {
		dfs1(1,0);
		sum = 0;
		memset(dist,0,sizeof(dist));
		dfs2(A,0);
		int cnt = dist[B];
		int u = B;
		do {
			mp[u][pre[u]] = -2;
			mp[pre[u]][u] = -2;
			u = pre[u];
		} while(pre[u] != A);
		dfs3(1,0);
		int ccnt = ans;
		cout << (n - 1) * 2 - cnt - ccnt + 2 << "\n";
	}
	return 0;
}
2025/1/19 08:25
加载中...