Update 3562_unfinished.cpp

This commit is contained in:
Kirigaya Kazuto 2016-10-12 10:21:16 +08:00 committed by GitHub
parent 197b491f4e
commit 4b9de74b62

View File

@ -1,91 +1,96 @@
#include <iostream>
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cmath>
#include <algorithm> #include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#define mod 1000000007
#define inf 0x3f3f3f3f
#define pi acos(-1.0)
using namespace std; using namespace std;
#define INF 0x3f3f3f3f typedef long long ll;
#define RANGE 1005
/** SPFA 单源最短路径算法 不支持负环*/ #define MAX 0x3f3f3f3f
#define MAXN 1005; int cost[RANGE][RANGE];
int d[MAXN];/// distance [ From S to ... ] int d[RANGE];
bool v[MAXN];/// visit bool used[RANGE];
int q[MAXN];/// 基于数组的队列(也可用queue等...) int n,m;
int mp[MAXN][MAXN]; /// mp[i][j] i<--> j is connected. int pre[1005];
int n,m;/// n is the number of max Point . void spfa(int s)
int path[MAXN];
void spfa(int StartPoint) /// d[i] is the min distance from StartPoint to i ( Both >=1 )
{ {
for(int i=0; i<=n; i++) int i,j,now;
{ for(i=0; i<=n+1; i++)
if(mp[0][i]!=INF)path[i]=i;//Path Init
d[i]=INF;
v[i]=0;
}
int cnt=0;
q[cnt++]=StartPoint;
v[StartPoint]=1;
d[StartPoint]=0;
while(cnt>0)
{ {
int c=q[--cnt]; d[i]=MAX;
//v[c]=0; used[i]=false;
for(int i=0;i<=n;i++) }
int flag=0;
for(i=0; i<=n+1; i++)
{
if(cost[0][i]<MAX)pre[i]=i;//初始化pre数组
}
used[s]=true;
d[s]=0;
queue<int> q;
q.push(s);
while(!q.empty())
{
now=q.front();
q.pop();
for(i=0; i<=n+1; i++)
{ {
/// Here : if your mp[i][j] use INF as infinite, then use mp[c][i]!=INF. if(d[i]>d[now]+cost[now][i])
/// Or you may use mp[i][j]!=-1 && d[i] > d[c] + mp[c][i]
if( d[i]>d[c]+mp[c][i] )
{ {
d[i]=d[c]+mp[c][i]; d[i]=d[now]+cost[now][i];
//path[i]=min(path[i],path[c]); if(used[i]==0)
if(!v[i])
{ {
if(c) path[i]=path[c]; if(now!=0)pre[i]=pre[now];
v[i]==1; used[i]==true;
q[cnt++]=i; q.push(i);
} }
} }
if(d[i]==d[now]+cost[now][i])
if(d[i]==d[c]+mp[c][i])
{ {
if(c)path[i]=min(path[i],path[c]); if(now!=0)pre[i]=min(pre[i],pre[now]);
} }
} }
} }
} }
int main() int main()
{ {
int t; int i,j,a,b,c;
scanf("%d",&t); int we;
while(t--) scanf("%d",&we);
while(we--)
{ {
scanf("%d%d",&n,&m); scanf("%d%d",&n,&m);
if(!n&&!m) break; if(!n&&!m) break;
n=n+1; for(i=0; i<=n+1; ++i)
for(int i=0;i<=n;++i)
{ {
for(int j=0;j<=i;++j) for(j=0; j<=i; j++)
{ {
if(i==j) mp[i][j]=0; if(i==j) cost[i][j]=0;
else mp[i][j]=mp[j][i]=INF; else cost[i][j]=cost[j][i]=MAX;
} }
} }
int tu,tv,tw; for(i=0; i<m; i++)
for(int i=0;i<m;i++)
{ {
scanf("%d%d%d",&tu,&tv,&tw); scanf("%d%d%d",&a,&b,&c);
mp[tu][tv]=tw; cost[a][b]=c;
} }
spfa(0); spfa(0);
if(d[n+1]<MAX)
if(d[n]<INF)
{ {
if(path[n]==n)printf("0\n"); if(pre[n+1]==n+1)printf("0\n");
else printf("%d\n",path[n]); else printf("%d\n",pre[n+1]);
} }
else printf("-1\n"); else printf("-1\n");
} }