USACO Section 3.2: Sweet Butter
2013-07-21 17:11
302 查看
这题我自己是用邻接矩阵+dijskstra方法来求的,第九个例子TLE。网上看了别人的代码,是用邻接表+BFS来完成。
这里可以学到两个小技巧,邻接表的表示方法和INT_MAX的表示方法。
这里可以学到两个小技巧,邻接表的表示方法和INT_MAX的表示方法。
/* ID:yingzho1 LANG:C++ TASK:butter */ #include<fstream> #include<cstring> #include<queue> #include <limits> using namespace std; ifstream fin("butter.in"); ofstream fout("butter.out"); const int MAX = 805; struct vertex { int end,len; }; vertex adj[MAX][MAX]; int cnt[MAX]={0}, cowpos[505]={0}, n, p, c; bool pushed[MAX]={0}; int distances[MAX]; int search(int start) { memset(pushed, 0, sizeof(pushed)); for(int k = 1; k <= p; k++) distances[k] = numeric_limits<int>::max(); queue<int> Q; Q.push(start); pushed[start] = true; distances[start] = 0; while(!Q.empty()) { int x = Q.front(); Q.pop(); pushed[x] = false; for(int j = 0; j < cnt[x]; j++) { if(distances[x]+adj[x][j].len < distances[adj[x][j].end]) { distances[adj[x][j].end] = distances[x]+adj[x][j].len; if(!pushed[adj[x][j].end]) { Q.push(adj[x][j].end); pushed[adj[x][j].end] = true; } } } } int ans = 0; for(int i = 1; i<=n; i++) { if(distances[cowpos[i]]==numeric_limits<int>::max()) return -1; else ans+=distances[cowpos[i]]; } return ans; } int main() { memset(cnt, 0, sizeof(cnt)); fin>>n>>p>>c; for(int i = 1; i<=n; i++) fin>>cowpos[i]; for(int i = 1, s, t, value; i <= c; i++) { fin>>s>>t>>value; adj[s][cnt[s]].end = t; adj[s][cnt[s]].len = value; cnt[s]++; adj[t][cnt[t]].end = s; adj[t][cnt[t]].len = value; cnt[t]++; } int res, mins = numeric_limits<int>::max(); for(int i = 1; i <= p; i++) { res = search(i); if(res < mins && res != -1) mins = res; } fout<<mins<<endl; return 0; }
相关文章推荐
- USACO Section 3.2 Sweet Butter (butter)
- USACO-Section 3.2 Sweet Butter(最短路[Dijkstra])
- USACO Section 3.2 Sweet Butter(SPFA)
- USACO Section 3.2 Sweet Butter - 还是SPFA好使..
- USACO-Section3.2 Sweet Butter【Dijkstra算法】
- USACO 3.2 Sweet Butter(SPFA)
- USACO 3.2 Sweet Butter
- USACO-Section 3.2 Magic Squares(BFS)
- USACO section 3.2 Factorials(dp)
- USACO Section 3.2 Stringsobits - 排列组合
- USACO section 3.2 Factorials(dp)
- USACO Training Section 3.2 & 洛谷P2730
- USACO section 3.2 Spinning Wheels(模拟)
- usaco Chapter 3 section 3.2 Feed Ratios
- USACO-Section3.2 Factorials【模拟法】
- USACO-Section3.2 Stringsobits【递归】
- USACO Section 3.2 Factorials(n!求最右边非零数)
- USACO section 3.2 Spinning Wheels(模拟)
- [USACO3.2]Sweet Butter
- USACO Section 3.2 Factorials