这样做是错的,为啥?......
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<set> 6 using namespace std; 7 const int maxn=207; 8 int n,m,ans; 9 int map[maxn][maxn]; 10 set<int>node[maxn][maxn]; 11 int a[maxn],top; 12 bool vis[maxn]; 13 int main(){ 14 memset(map,0x3f3f3f3f,sizeof(map)); 15 cin>>n>>m; 16 for(int i=1;i<=m;i++){ 17 int u,v,w;cin>>u>>v>>w; 18 map[u][v]=map[v][u]=w; 19 } 20 for(int k=1;k<=n;k++){ 21 for(int i=1;i<=n;i++){ 22 for(int j=i+1;j<=n;j++){ 23 if(map[i][j]>map[i][k]+map[k][j]){ 24 map[i][j]=map[i][k]+map[k][j]; 25 node[i][j].clear(); 26 node[i][j].insert(k); 27 } 28 else if(map[i][j]==map[i][k]+map[k][j]&&node[i][j].count(k)) {node[i][j].clear();node[i][j].insert(k);} 29 else if(map[i][j]==map[i][k]+map[k][j]&&!node[i][j].count(k)) {node[i][j].clear();} 30 } 31 } 32 } 33 for(int k=1;k<=n;k++){ 34 for(int i=1;i<=n;i++){ 35 for(int j=1;j<=n;j++){ 36 if(node[i][j].count(k)) a[++top]=k; 37 } 38 } 39 } 40 sort(a+1,a+top+1); 41 int sz=unique(a+1,a+top+1)-a-1; 42 for(int i=1;i<=sz;i++) cout<<a[i]<<" "; 43 return 0; 44 }
然后最开始写的这种方法和题解一样,觉得有问题......
有一些小错误,写的不对
题解
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 const int maxn=207; 6 int n,m,ans; 7 int map[maxn][maxn],node[maxn][maxn]; 8 int a[maxn],top; 9 bool vis[maxn],flag; 10 int main(){ 11 cin>>n>>m; 12 memset(map,0x3f3f3f,sizeof(map)); 13 for(int i=1;i<=n;i++) map[i][i]=0; 14 for(int i=1;i<=m;i++){ 15 int u,v,w;cin>>u>>v>>w; 16 map[u][v]=map[v][u]=w; 17 } 18 for(int k=1;k<=n;k++){ 19 for(int i=1;i<=n;i++){ 20 if(k==i) continue; 21 for(int j=1;j<=n;j++){ 22 if(k==j||j==i) continue; 23 if(map[i][j]>map[i][k]+map[k][j]){ 24 map[i][j]=map[i][k]+map[k][j]; 25 node[i][j]=k; 26 } 27 else if(map[i][j]==map[i][k]+map[k][j]) {node[i][j]=-1;} 28 } 29 } 30 } 31 for(int i=1;i<=n;i++){ 32 for(int j=1;j<=n;j++){ 33 if(node[i][j]!=-1) vis[node[i][j]]=true; 34 } 35 } 36 for(int i=1;i<=n;i++) 37 if(vis[i]) {cout<<i<<" ";flag=true;} 38 if(!flag) cout<<"No important cities."; 39 cout<<endl; 40 return 0; 41 }