Holylight_Knight

某神犇:自己选择的路,跪着也要走完。

poj之旅——3259,3268

基础模板题。

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;
}

阅读更多
版权声明:本文为博主原创文章,但可以随意转载 https://blog.csdn.net/no1_terminator/article/details/51537047
上一篇图论之最短路问题
下一篇poj之旅——1258,2377,2395
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭