PATA 1018 문제 풀이

2483 단어 PAT
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 510;
const int inf = 1000000000;
int Cmax, n, Sp, m, prefect;
int G[maxn][maxn];
int d[maxn], c[maxn];
bool vis[maxn] = {false};
vector pre[maxn];

void dijkstra(int s) {
	fill(d, d + maxn, inf);
	d[s] = 0;
	for(int i = 0; i <= n; i++) {
		int u = -1, MIN = inf;
		for(int j = 0; j <= n; j++) {
			if(vis[j] == false && d[j] < MIN) {
				u = j;
				MIN = d[j];
			}
		}
		if(u == -1) return;
		vis[u] = true;
		for(int v = 0; v <= n; v++) {
			if(vis[v] == false && G[u][v] != inf) {
				if(d[u] + G[u][v] < d[v]) {
					pre[v].clear();
					d[v] = d[u] + G[u][v];
					pre[v].push_back(u);
				} else if(d[u] + G[u][v] == d[v]) {
					pre[v].push_back(u);
				}
			}
		}
	}
}

vector temp, path;
int optvalue = inf, optback = inf;
void DFS(int v) {
	if(v == 0) {
		temp.push_back(v);
		int value = 0, need = 0, k = 1, back = 0;
		int station = temp.size() - 1;
		for(int i = temp.size() - 2; i >= 0; i--) {
			value += c[temp[i]];
			if(prefect * k - value > need) {
				need = prefect * k - value;
			}
			k++;
		}
		back = need + value - (temp.size() - 1) * prefect;
		if(back < 0) back = 0;
		if(need < optvalue) {
			optvalue = need;
			optback = back;
			path = temp;
		} else if(need = optvalue) {
			if(back < optback) {
				path = temp;
				optback = back;
			}
		}
		temp.pop_back();
		return;
	}
	temp.push_back(v);
	for(int i = 0; i < pre[v].size(); i++) {
		DFS(pre[v][i]);
	}
	temp.pop_back();
}

int main() {
	scanf("%d %d %d %d", &Cmax, &n, &Sp, &m);
	for(int i = 1; i <= n; i++) {
		scanf("%d", &c[i]);
	}
	prefect = Cmax / 2;
	fill(G[0], G[0] + maxn * maxn, inf);
	for(int i = 0; i < m; i++) {
		int a, b, dis;
		scanf("%d %d %d", &a, &b, &dis);
		G[a][b] = G[b][a] = dis;
	}
	dijkstra(0);
	DFS(Sp);
	printf("%d ", optvalue);
	//int back = 0, total = 0;
	for(int i = path.size() - 1; i >= 0; i--) {
	//	if(i != path.size() - 1) total += c[path[i]];
		printf("%d", path[i]);
		if(i != 0) printf("->");
		else printf(" ");
	}
	//back = optvalue + total - prefect * (path.size() - 1);
	printf("%d", optback);
	return 0;
}


/*
10 5 5 6
3 4 8 6 0
0 1 1
0 2 1
1 3 1
2 4 1
3 5 1
4 5 1
*/

좋은 웹페이지 즐겨찾기