关闭

poj之旅——3259,3268

55人阅读 评论(0) 收藏 举报
分类:

基础模板题。

3259:

#include<cstdio>
#include<algorithm>
#include<cstring>
#define maxm 10000
#define INF 0x3f3f3f3f
int d[maxm];
int cnt,n,m,w;
struct Edge{
	int from,to,dist;
}e[maxm];
void addedge(int u,int v,int w){
	e[cnt].from=u;
	e[cnt].to=v;
	e[cnt++].dist=w;
}
bool find_negative_loop(){
	memset(d,0,sizeof(d));
	for (int i=0;i<n;i++)
		for (int j=0;j<cnt;j++){
			Edge t=e[j];
			if (d[t.to]>d[t.from]+t.dist){
				d[t.to]=d[t.from]+t.dist;
				if (i==n-1)return true;
			}
		}
    return false;		
}
int main(){
	int T;
	scanf("%d",&T);
	while (T--){
		scanf("%d%d%d",&n,&m,&w);
		int u,v,cost;
		cnt=0;
		for (int i=0;i<m;i++){
			scanf("%d%d%d",&u,&v,&cost);
			u--;v--;
			addedge(u,v,cost);
			addedge(v,u,cost);
		}
		for (int i=0;i<w;i++){
			scanf("%d%d%d",&u,&v,&cost);
			u--;v--;
			addedge(u,v,-cost);
		}
		if (find_negative_loop())printf("YES\n");
			else printf("NO\n");
	}
	return 0;
}

3268:

#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<vector>
#define maxn 10000
#define INF 0x7f7f7f7f
using namespace std;
int n,m,id;
struct Edge{
	int from,to,dist;
	Edge(int from,int to,int dist):from(from),to(to),dist(dist){}
};
struct HeapNode{
	int d,u;
	bool operator < (HeapNode rhs)const{
		return d>rhs.d;
	}
	HeapNode(int d,int u):d(d),u(u){};
};
struct Dijkstra{
	int n,m;
	vector<Edge> edges;
	vector<int> G[maxn];
	bool done[maxn];
	int d[maxn];
	int p[maxn];
	void init (int n){
		this->n=n;
		for (int i=0;i<n;i++) G[i].clear();
		edges.clear();
	}
	void addedge(int from,int to,int dist){
		edges.push_back(Edge(from,to,dist));
		m=edges.size();
		G[from].push_back(m-1);
	}
	void dijsktra(int s){
		priority_queue<HeapNode> Q;
		for (int i=0;i<n;i++) d[i]=INF;
		d[s]=0;
		memset(done,0,sizeof(done));
		Q.push(HeapNode(0,s));
		while (!Q.empty()){
			HeapNode x=Q.top();Q.pop();
			int u=x.u;
			if (done[u])continue;
			done[u]=true;
			for (int i=0;i<G[u].size();i++){
				Edge e=edges[G[u][i]];
				if (d[e.to]>d[u]+e.dist){
					d[e.to]=d[u]+e.dist;
					p[e.to]=G[u][i];
					Q.push(HeapNode(d[e.to],e.to));
				}
			}
	    }
	}
}G1,G2;
int main(){
	scanf("%d%d%d",&n,&m,&id);
	id--;
	G1.init(n);G2.init(n);
	for (int i=0;i<m;i++){
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		u--;v--;
		G1.addedge(u,v,w);
		G2.addedge(v,u,w);
	}
	G1.dijsktra(id);
	G2.dijsktra(id);
	int ans=G1.d[0]+G2.d[0];
	for (int i=1;i<n;i++)ans=max(ans,G1.d[i]+G2.d[i]);
	printf("%d",ans);
	return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20208次
    • 积分:1745
    • 等级:
    • 排名:千里之外
    • 原创:153篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条