P8564(csp-s模拟赛T2) 求助
  • 板块学术版
  • 楼主ParanoidMO
  • 当前回复0
  • 已保存回复0
  • 发布时间2022/10/4 19:46
  • 上次更新2023/10/27 08:48:37
查看原帖
P8564(csp-s模拟赛T2) 求助
218188
ParanoidMO楼主2022/10/4 19:46
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e3+10;
const int inf = 1e9+7;
int n, f[maxn], sub[maxn], dp[maxn][2], refx[maxn];
vector<int> G[maxn];

int dfs(int x, int fa){
	if (G[x].size() == 1) dp[x][1] = inf;
	for (int i=0; i<G[x].size(); i++){
		int v = G[x][i];
		if (v == fa) continue;
		sub[x] += dfs(v, x);
	}
	return sub[x];
}

string cvt(int x, int sz){
	string cnt = "";
	int ct = 0;
	while (x){
		if (x&1) cnt += '1';
		else cnt += '0';
		x >>= 1; 
		ct ++;
	}
	for (int i=ct; i<sz; i++) cnt += '0';
	return cnt;
}

void search(int x, int fa){
	int rsz=0, ssz=0;
	for (int i=0; i<G[x].size(); i++){
		int v = G[x][i];
		if (v == fa) continue;
		search(v, x);
	}	
	for (int i=0; i<G[x].size(); i++) {
		int v = G[x][i];
		if (v == fa) continue;
		if (dp[v][1] >= inf) {
			++ssz;
			continue;
		}
		refx[++rsz] = v;
	}
	for (int i=0; i<pow(2, rsz); i++){
		int sum = rsz, res = 0, sz = 0, flag=0;
		string num = cvt(i, rsz);
		for (int j=1; j<=rsz; j++){
			int v = refx[j];
//			cout<<v<<" j:"<<j<<endl;
			if (num[j-1] == '0'){
				 res += dp[v][1];
//				 cout<<"not selected:"<<v<<endl;
				 if (res >= inf) {
				 	flag = 1;
				 	break;
				 }
			}
			else if (num[j-1] == '1'){
				sz += sub[v]; sum --;
//				cout<<"selected:"<<v<<" j:"<<j<<endl;
			}
		}
		if (flag) continue;
		res += f[sz+sum+ssz+1];
//		cout<<x<<" sz:"<<sz<<" sum:"<<sum<<" res:"<<res<<endl;
//		cout<<dp[x][1]<<" lst:"<<num<<" "<<rsz<<" ind:"<<sz+sum+ssz+1<<endl;
//		cout<<cvt(i, rsz)<<" i:"<<i<<endl;
		dp[x][1] = min(dp[x][1], res);
//		cout<<"final:"<<dp[x][1]<<endl<<endl; 
	}
}

int main(){
	ios::sync_with_stdio(false);
//	freopen("T2ex2.in", "r", stdin);
//	freopen("out.txt", "w", stdout);
	cin>>n;
	f[1] = inf;
	for (int i=1; i<n; i++) cin>>f[i+1];
	for (int i=1; i<n; i++){
		sub[i] = 1; dp[i][1] = inf;
		int u, v; cin>>u>>v;
		G[u].push_back(v);
		G[v].push_back(u);
	}
	sub[n] = 1; dp[n][1] = inf;
	dfs(1, -1);
	search(1, -1);
	cout<<dp[1][1]<<endl;
//	system("pause");
} 

ex1能过,ex2寄了,15pts,求助是算法有误还是写寄了

2022/10/4 19:46
加载中...