poj2531-dfs
Run time error了
不知道哪里做错
知道后立即修改博客
先交解题报告打卡
#include <iostream> using namespace std; class Node{ public: int* messageNode; bool visited; int group; Node(int nodeSum=0){ visited = false; group = 0; if(nodeSum != 0) messageNode = new int[nodeSum]; } }; int nSum = 0; Node **nodeQueue; int amount = 0; int countNode = 0; bool nodeGroup = false; int *divideGroup; void dfs(int x){ countNode++; if(countNode <= nSum){ nodeQueue[x]->visited = true; if(!nodeGroup){ divideGroup[x] = 0; nodeGroup = true; } else{ divideGroup[x] = 1; nodeGroup = false; } int largest = -1; int temp = 0; for(int i=0;i < nSum;i++){ if(!nodeQueue[i]->visited && nodeQueue[x]->messageNode[i] > temp){ largest = i; temp = nodeQueue[x]->messageNode[i]; } } dfs(largest); } } void calculateAll(){ for(int i=0;i<nSum;i++){ if(divideGroup[i] == 0){ for(int j=0;j<nSum;j++){ if(divideGroup[j] == 1) amount += nodeQueue[i]->messageNode[j]; } } } cout << amount << endl; } int main() { cin >> nSum; if(nSum >0){ nodeQueue = new Node*[nSum]; divideGroup = new int[nSum]; for(int i=0;i<nSum;i++){ nodeQueue[i] = new Node(nSum); divideGroup[i] = -1; for(int j=0;j<nSum;j++) { cin >> nodeQueue[i]->messageNode[j]; } } dfs(0); calculateAll(); } return 0; }
其他的正解
//
// main.cpp
// poj2531Cpp_others
//
// Created by 韩雪滢 on 12/1/16.
// Copyright © 2016 韩雪滢. All rights reserved.
//
#include <iostream>
using namespace std;
const int MAX_N = 20;
int n;
int map[MAX_N + 1][MAX_N + 1];
bool in_group[MAX_N + 1];
int ans;
void dfs(int id, int cur_sum)
{
in_group[id] = true;
int tmp_sum = cur_sum;
for (int i = 1; i <= n; i++){
if (in_group[i]){
tmp_sum -= map[id][i];
}
else{
tmp_sum += map[id][i];
}
}
if (tmp_sum > ans){
ans = tmp_sum;
}
//剪枝:当前的sum大时
if (tmp_sum > cur_sum){
//id之前的会重复,舍掉
for (int i = id + 1; i <= n; i++){
dfs(i, tmp_sum);
}
}
in_group[id] = false;
}
int main()
{
cin >> n;
memset(in_group, 0, sizeof(in_group));
ans = 0;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
cin >> map[i][j];
}
}
dfs(1, 0);
cout << ans << endl;
return 0;
}