C - TT 的美梦

题意介绍

有若干城市,从一个城市到另一个城市需要交税(可能为负值),求给出城市到首都索要交的税。

题意分析

该题要求单源最短路径,并且存在负边的情况,只能用SPFA算法。在SPFA时要将存在与负环中的点标记出来,判断负环的条件为点出现在队列中的次数大于等于中的点数。输出"?"的条件为该点出现在负环中或者不可到达或者要缴纳的税小于3.

#include<iostream>
#include<string.h>
#include<queue>
using namespace std;

const int inf=0x3f3f3f3f;

int t, n, m, u, v, q, p;
int a[210];
int head[210], tot;
queue<int> que;
int dis[210], inq[210], cnt[210],vis[210];

struct edge {
	int to, next, w;
}edge[100010];

void init() {
	tot = 0;
	memset(head, -1, sizeof(head));
}

void add(int x, int y, int w) {
	edge[tot].to = y;
	edge[tot].w = w;
	edge[tot].next = head[x];
	head[x] = tot;
	tot++;
}

void dfs(int u) {
	
	vis[u] = 1;
	for (int i = head[u]; i != -1; i = edge[i].next) {
		if(vis[edge[i].to]==0)
		dfs(edge[i].to);
	}
}

void spfa(int s) {
	while (!que.empty()) que.pop();
	for (int i = 1; i <= n; i++) {
		dis[i] = inf;
		inq[i] = 0;
		cnt[i] = 0;
		vis[i] = 0;
	}
	dis[s] = 0;
	inq[s] = 1;
	que.push(s);

	while (!que.empty()) {
		int u = que.front();
		que.pop();
		inq[u] = 0;

		for (int i = head[u]; i != -1; i = edge[i].next) {
			int v = edge[i].to, w = edge[i].w;
			if (vis[v]) continue;
			if (dis[v] > dis[u] + w) {
				dis[v] = dis[u] + w;
							
				if (!inq[v]) {
					que.push(v);
					inq[v] = 1;
					cnt[v]++;
					if (cnt[v] >= n) {//找到负环
						dfs(v);
					}
				}
			}
		}
	}
}
int main() {
	cin >> t;
	int item = 1;
	while (t--) {
		cin >> n;
		for (int i = 1; i <= n; i++) cin >> a[i];

		init();
		cin >> m;		
		for (int i = 0; i < m; i++) {
			cin >> u >> v;
			add(u, v, (a[v] - a[u])*(a[v] - a[u])*(a[v] - a[u]));
						
		}

		spfa(1);

		cout << "Case" << " " << item << ":"<<endl;
		cin >> q;
		while (q--) {
			cin >> p;
			if (vis[p] == 0) {
				//cout << dis[p] << endl;
				if (dis[p] < 3||dis[p]==inf)cout << "?" << endl;
				else cout << dis[p] << endl;
			}
			else
				cout << "?" << endl;
		}
		item++;
	}
	return 0;
}```

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值